Hi,
I want to convert some date strings into correct dates, to be recognized by Python and ArcGIS.
Setup:
ArcGIS 10.2.1
Python 2.7.5
All data are located within a FGDB...
I set the workspace to be the FGDB, created a new Field of type data in my table and went on with the following things within the IDLE Shell
import datetime
with arcpy.da.UpdateCursor(myTable, [field01, field02]) as UCursor:
for row in UCursor:
origDate = datetime.datetime.strptime(row[0], '%d%b%Y')
row[1] = datetime.date.strftime(origDate, '%Y-%m-%d')
UCursor.updateRow(row)
Things work fine until the input string is '11MAY2004', where I get the following error message:
Traceback (most recent call last):
File "<pyshell#9>", line 4, in <module>
origDate = datetime.datetime.strptime(row[0], '%d%b%Y')
File "C:\Python27\ArcGISx6410.2\lib\_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '11MAY2004' does not match format '%d%b%Y'
I did try the whole thing in plain Python (same shell) before, where I simply did:
orig = '11MAY2004'
x = datetime.datetime.strptime(orig, '%d%b%Y')
and this works without any problem!!!
Can somebody enlighten me where I go wrong?
Cheers, Thomas
Hi Thomas,
I suspect it's your locale setting. I can reproduce the same error if i set my locale explicitly to German_Germany, may be try explicitly setting your locale as
locale.setlocale(locale.LC_ALL, 'English_US')
Below is the code that produced this error.
import arcpy, datetime, locale
layer = arcpy.GetParameter(0)
arcpy.AddMessage(layer)
locale.setlocale(locale.LC_ALL, 'German_Germany')
with arcpy.da.UpdateCursor(layer, ["ddMMMYYYY", "YYYY_MM_dd"]) as UCursor:
for row in UCursor:
origDate = datetime.datetime.strptime(row[0], '%d%b%Y')
row[1] = datetime.date.strftime(origDate, '%Y-%m-%d')
UCursor.updateRow(row)
Hi,
yes I can confirm that is has something to do with locale. A first solution was to change the format localization from Danish to English and restart the shell. I have to follow up on your suggestion to use the locale package. Thanks so far.
Thomas
I get an error with strftime if I try to use %T, which according to TutorialsPoint is a valid format, a shortcut for %H%M%S.
But this raises an error, and in fact is not in the Python.org documentation for strftime. The point being that there's erroneous information out on the web. Who knew?
If it's a locale issue, you may want to look at:
strftime() returns a locale depedent byte string; the result may be converted to unicode by doing strftime(<myformat>).decode(locale.getlocale()[1]).
also from the same documentation.
Hi Greg,
never saw a '%T' and hey Tutorialspoint is a nice starting but nothing official and I would rather stick to the official docs. I solved the problem quick and dirty, and the task is pushing me further, but as soon as I have the time to check on locale and decode I will give it a try.
Bests, Thomas