3

I am trying to convert the following code to python. DATE_VAL is a date field. I want to add 12 hours to the date. I have ArcGIS Desktop 10.4.1 and python 2.7.1.

arcpy.CalculateField_management("all_reports.gdb\\lsr_reports6", "NEW_DATE", "DateAdd(\"h\", 12, [DATE_VAL])", "", "")

Not working:

arcpy.CalculateField_management("all_reports.gdb\\lsr_reports6", "NEW_DATE", "!DATE_VAL! + datetime.timedelta(hours=12)", "PYTHON_9.3", "")
3

When you get the value !DATE_VAL! ArcMap returns a string. You have to therefore construct a datetime object in order to add a timedelta object. To do this, you need to know the format of the string returned by your Date field. By default, ArcMap uses your system date format.

In my case, I have the DATE_VAL field which returns dates in the format 14/10/2016 15:00:00. Therefore, to increment by 12 hours, I used the following expression:

datetime.datetime.strptime(!DATE_VAL!,'%d/%m/%Y %H:%M:%S') + datetime.timedelta(hours=12) 

I recommend reading the ArcMap Fundamentals of date fields and the python documentation on the datetime module, particularly strftime-and-strptime-behavior.

2

See my blog on "I've Saved Time in a Bottle. How Do I Get it Back Out? - Doing More with Date Fields Using the Field Calculator and Python"

As stupid as it may seem, when you use the Python option in the Field Calculator on a date field, the date is converted to a string and does not have any native date functionality. You have to convert it back to a datetime before doing any date or time manipulations or formatting. The Blog provides a method to do that and examples of date manipulations (although not the one you want to do specifically).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.