Reputation: 31
I am trying to convert a string to datetime and it isn't working...
self.loadsList[loadID][5] = datetime.strptime(
self.loadsList[loadID][5]+" "+self.loadsList[loadID][6], "%x %X %z")
and it raises a Value Error.
ValueError: time data '11/08/2014 04:00:00 -0500' does not match format '%x %X %z'
What am I doing wrong? Thanks! (Python 3.4)
Upvotes: 3
Views: 1689
Reputation: 1124538
The default %x
format is the equivalent of %d/%m/%y
, where %y
matches a two digit year:
>>> import locale
>>> locale.nl_langinfo(locale.D_FMT)
'%m/%d/%y'
Your input uses a 4 digit year instead:
>>> from datetime import datetime
>>> datetime.strptime('11/08/2014', '%x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 340, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 14
I'd not use %x
or %X
, just spell out the date and time formats; based on your input and the use of %x
that'd be:
'%m/%d/%Y %H:%M:%S %z'
Demo:
>>> datetime.strptime('11/08/2014 04:00:00 -0500', '%m/%d/%Y %H:%M:%S %z')
datetime.datetime(2014, 11, 8, 4, 0, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))
It is not clear if your input represents the 8th day of November or the 11th day of August; your use of %x
suggests the former but I suspect you should instead interpret the value the other way around:
'%d/%m/%Y %H:%M:%S %z'
The alternative would be to switch your Python locale from the default C
to en_US
where the year would use 4 digits.
Upvotes: 3