Select to view content in your preferred language

Field Calculator with Python parser convert text to date

1092
7
09-20-2022 11:44 AM
2Quiker
Frequent Contributor

I need to convert a text field "Year1" into a date filed (Year1) with just the year.

Field Year is a text field, with just a year date, "2015" and field Year1 is a date field.

 

 

from datetime import datetime
from datetime import time
import datetime as dt
from time import gmtime, strftime
def calcYear():
    fc = "Lyr"
    #testdate = '04/25/2015'
    with arcpy.da.UpdateCursor(fc,['Year','Year1']) as cursor:
        for row in cursor:
            if row[0] not in (""," ",None):
                d1 = datetime.strptime(datetime.strftime(row[0], "%Y"), "%Y")         
                row[1] = d1.year
                cursor.updateRow(row)

 

I get the following error. I was thinking that line 11 was converting the text  into a day(year).

ERROR 000539: Traceback (most recent call last):
File "<expression>", line 1, in <module>
File "<string>", line 11, in calcYear
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'int'
Failed to execute (Calculate Field

0 Kudos
7 Replies
by Anonymous User
Not applicable

The strftime() method returns a string representing date and time using date, time or datetime object. Try just strptime.

 

d1 = datetime.strptime(row[0], "%Y") 

 

 

Edit to add:

This will return 2015-01-01 00:00:00

You can get the year with dot notation, but it is an int.

d1 = datetime.strptime(xd, "%Y").year

 

2Quiker
Frequent Contributor

Thanks fro the replay.

 

Tried the following but nothing happens, no print, no error.

 

 

 

def calcYear():
    fc = "Lyr"
    #testdate = '04/25/2015'
    with arcpy.da.UpdateCursor(fc,['Year','Year1']) as cursor:
        for row in cursor:
            if row[0] not in (""," ",None):
                d1 = datetime.strptime(row[0],"%Y").year     
                print(d1)  #"{}".formate(d1)
                row[1] = d1
                cursor.updateRow(row)

 

 

 

0 Kudos
by Anonymous User
Not applicable

You need to format it to match the input date format so if your date is mm/dd/YYYY, you'll use %m/%d/%Y:

 

d1 = datetime.strptime(row[0], "%m/%d/%Y").year
2Quiker
Frequent Contributor

My apologizes for number of responses.

So field "Year" has just years, 2015,1997, 2022, etc and is a "text" field. It doesn't have month or days

When I replace the "%Y" with "%m/%d/%Y"

d1 = datetime.strptime(row[0], "%m/%d/%Y").year

 

I get;

ERROR 000539: Traceback (most recent call last):
File "<expression>", line 1, in <module>
File "<string>", line 11, in calcYear
TypeError: strptime() argument 1 must be str, not int
Failed to execute

 

If i use the following

from datetime import datetime
from datetime import time
import datetime
def calcYear():
    fc = "Lyr"
    #testdate = '04/25/2015'
    with arcpy.da.UpdateCursor(fc,['Year','Year1']) as cursor:
        for row in cursor:
            if row[0] not in (""," ",None):
                d1 = datetime.datetime.strptime("{}".format(row[0]),"%Y").year         
                return d1
                #formattedTime = datetime.datetime.strptime("{}".format(!Year!), "%Y")
                #row[1] = d1
                #cursor.updateRow(row)

 

I get Value = 1997

the Field "Year1" doesn't get updated

 

I tested this in python window

import arcpy
from datetime import datetime
from datetime import time
import datetime
#def calcYear():
fc = "Lyr"
#testdate = '04/25/2015'
with arcpy.da.UpdateCursor(fc,['Year','Year1']) as cursor:
    for row in cursor:
        if row[0] not in (""," ",None):
            d1 = datetime.datetime.strptime("{}".format(row[0]),"%Y").year         
            print (d1)
            #formattedTime = datetime.datetime.strptime("{}".format(!Year!), "%Y")
            row[1] = d1
            cursor.updateRow(row)

  I get the year printed

2022
2022
2022
2022
2022
2022
2022
2007

But the field "Year1" doesn't get populated/updated.

 

2022-09-20 16_19_04-.png

0 Kudos
by Anonymous User
Not applicable

Spaced that you are doing this in a field calculator. You don't use a cursor in a field calculator because it will iterate over all features for each feature. Field Calculator has its own iterator so you do not have to set it.

 

Create the calculator on the target date field. Pass in the string field and return the value.

calcYear(!Year!)

 

import datetime
def calcYear(strYear):
    return datetime.datetime.strptime(strYear, '%Y')

 

2Quiker
Frequent Contributor

Sorry for the delay, I got caught up.

I get the following with what you suggested.

ERROR 000539: Traceback (most recent call last):
File "<expression>", line 1, in <module>
File "<string>", line 3, in calcYear
TypeError: strptime() argument 1 must be str, not int

 

I get the following If I do this .

WARNING 002858: Certain rows set to NULL due to error while evaluating python expression: File "<string>", line 3, in calcYear

 

calcYear(!Year!)
import datetime
def calcYear(strYear):
    return datetime.datetime.strptime("{}".format(strYear), '%Y') 

 

 

There is nulls in this field, how do I get past those nulls?

import datetime
def calcYear(strYear):
    if (strYear == None):
        return 0
    else:
        return datetime.datetime.strptime("{}".format(strYear), '%Y') 
0 Kudos
JoshuaBixby
MVP Esteemed Contributor

If strYear is None, why not just return None so the date has NULL since the year has NULL?

0 Kudos