2

I have a Date field in an ArcGIS file geodatabase feature class called "DateTemp1." I created a new text field called "DateTemp2" and want to calculate that based on the DateTemp1 field, but I am getting a unicode error.

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'unicode'

 arcpy.CalculateField_management("all_reports.gdb/lsr_reports1", "DateTemp2", "datetime.datetime.strftime(!DateTemp1!, '%Y%m%d')", "PYTHON_9.3", "")
4
  • No that did not work. I edited my question to include the error message. Thank you.
    – Andrew
    May 3, 2016 at 20:10
  • 1
    Have you considered the Convert Time Field tool? (ArcGIS 10.3+)
    – nmpeterson
    May 3, 2016 at 20:28
  • Your chosen solution works well if you need to control the exact format, but keep in mind that the error you received originally is caused by the fact that CalculateField passes the date field as a string into Python. In other words, you could have simply used the expression !DateTemp1! and you would have gotten a string formatted using the default expression (usually MM/DD/YYYY). May 4, 2016 at 12:33
  • You're right I tried that as well and it did work. The string was formatted MM/DD/YYYY as you stated. I do want the final string to be in the format YYYYMMDD. Using Convert Time Field it keeps the hours and minutes (YYYYMMDDHHMM). Now I am just trying to figure out how to dump the HHMM and create a new field, but that is another question. Thanks.
    – Andrew
    May 4, 2016 at 15:15

2 Answers 2

2

I looked into using the Convert Time Field tool as the poster suggested and it worked.

inTable  = "all_reports.gdb/lsr_reports1"
inputTimeField = "DateTemp1"
inputTimeFormat ="dd/MM/yyyy HH:mm:ss;AM;PM"
outputDateField = "DateTemp2"
arcpy.ConvertTimeField_management(inTable, inputTimeField, inputTimeFormat, outputDateField)
1

Try using "datetime.datetime.strptime( !DateTemp1! , '%d/%m/%Y').strftime('%Y%m%d')" as your expression:

arcpy.CalculateField_management("all_reports.gdb/lsr_reports1", "DateTemp2", "datetime.datetime.strptime( !DateTemp1! , '%d/%m/%Y').strftime('%Y%m%d')", "PYTHON_9.3", "")

NOTE you will need to change the '%d/%m/%Y' from in strptime( !DateTemp1! , '%d/%m/%Y') to match the current format of your existing date field

1
  • This works well too. I am going with this but I had to change the syntax to match the existing date field. "datetime.datetime.strptime( !DateTemp1! , '%d/%m/%Y %I:%M:%S %p').strftime('%Y%d%m')"
    – Andrew
    May 4, 2016 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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