5

Trying to convert a string to datetime and save it to db. The string specifies the timezone, but strptime doesn't accept the %z option.

datetime.strptime("Tue Feb 14 2017 15:30:01 GMT-0500", "%a %b %d %Y %H:%M:%S GMT%z")

ValueError: 'z' is a bad directive in format '%a %b %d %Y %H:%M:%S GMT%z'

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
Srini K
  • 3,315
  • 10
  • 37
  • 47
  • The answer looks to be here: http://stackoverflow.com/questions/26165659/python-timezone-z-directive-for-datetime-strptime-not-available – Marviel Feb 16 '17 at 15:51

1 Answers1

5

%z is supported since Python 3.2.

>>> from datetime import datetime
>>> datetime.strptime("Tue Feb 14 2017 15:30:01 GMT-0500", "%a %b %d %Y %H:%M:%S GMT%z")
datetime.datetime(2017, 2, 14, 15, 30, 1, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))

Or use dateutil.parser,

>>> from dateutil import parser
>>> parser.parse('Tue Feb 14 2017 15:30:01 GMT-0500')
datetime.datetime(2017, 2, 14, 15, 30, 1, tzinfo=tzoffset(None, 18000))

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134