I am having a heck of a time with this in field calculator and I've looked at the threads in geonet on datetime to string but none them seem to work for me. The ultimate goal is that I need to get a value out of datetime as an integer (so month would come through as an integer value of 2 for February for example). Since datetime seems to be formatted as a unicode string in Field Calculator, I think I need to get it to a regular string and then split it on the slashes so I can get the number I want and convert it to an integer before returning it. I have tried so many different solutions I couldn't write them all down here... can someone help me with this?
Date field is "Actual_Completion" and contains values displayed like so: 12/1/2015
(Long) Integer field is "Month" and needs the end value to be like so: 12
The closest I've gotten is this:
int(str(!Actual_Completion!)[0])
and it will return the first value of the month, but that's problematic for returning something like 12.
If I try
def getMonth():
x = str(!Actual_Completion!).split("/")
x = int(x[0])
return x
I get an invalid syntax error on line 2.
I've tried many different iterations of this:
from datetime import datetime
def getMonth(dateObj):
x = datetime.strftime(dateObj, '%m')
return int(x)
I get an error about strftime needing a datetime object and not a unicode object.
Solved! Go to Solution.
The following should work for you:
int(!Actual_Completion!.split("/")[0])
So while you can't cast the !Actual_Completion! field to a string directly using str() unless it's in an int() function for some reason I don't understand, I encoded the unicode value so it was a plain string and got it to work.
Codeblock:
def getMonth(dateField):
dateString = dateField.encode('UTF8')
dateParts = dateString.split("/")
return int(dateParts[0])
Are you working with ArcMap or Pro? The way each application handles ArcGIS Dates in Field Calculator differs.
ArcMap 10.7
The following should work for you:
int(!Actual_Completion!.split("/")[0])
Interesting, that does work. Why is it thought that it can take unicode and go directly to integer? Guess I need to do more reading about unicode...
Your issue wasn't really Unicode related. Both Unicode and String are sequences, which means they can be indexed and sliced. Looking at your first example:
int(str(!Actual_Completion!)[0])
!Actual_Completion! is returning a Unicode, str() is converting that to String, and then you are taking the first character of the string sequence. What you needed to do is split the Unicode/string based on forward slashes and then retrieve the first item from the tuple returned from splitting the text up.