AnsweredAssumed Answered

Datetime to String or Datetime to Integer

Question asked by MollyKFoley on Sep 5, 2019
Latest reply on Sep 5, 2019 by bixb0012

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:


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.