0

I am using the following format to convert the string into a datetime object.

datetime.datetime.strptime(systemTime, '%a %b %d %H:%M:%S %Z %Y')

I tested it for systemTime="Wed Jan 05 06:10:01 GMT 2005" and it worked fine. But when I tried systemTime="Wed Oct 02 18:01:56 EDT 2013", it failed with a ValueError:

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)
  File "SimpleWebServer.py", line 146, in startUDPServer
    ESTTime = datetime.datetime.strptime(systemTime, '%a %b %d %H:%M:%S %Z %Y')
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Wed Oct 02 18:01:56 EDT 2013' does not match format '%a %b %d %H:%M:%S %Z %Y'

The locale on machine is 'en US'. Is there anything wrong with my format?

  • the problem is with placing the EDT there in the string. – Patrick Bassut Oct 02 '13 at 22:23
  • Python itself does not provide parsing timezone aware datetime objects, instead it relies on external libraries. See [this](http://stackoverflow.com/questions/13182075/how-to-convert-a-timezone-aware-string-to-datetime-in-python-without-dateutil) question. – zaquest Oct 02 '13 at 22:35

2 Answers2

0

Python won't parse EDT. UTC works though.

from datetime import datetime
fmt = '%a %b %d %H:%M:%S %Z %Y'
t = "Wed Oct 02 18:01:56 UTC 2013"
print datetime.strptime(t, fmt)

Results in a valid datetime object

datetime.datetime(2013, 10, 2, 18, 1, 56)

Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46
0

The dateutil package has hooks for extending timezone handling, but does not parse EDT - it parses the rest of the date and leaves the timezone empty. You could use it and add the timezones for your application.

Noah Hafner
  • 341
  • 2
  • 5