I want to compute the UNIX time out of a string in Python. My string contains both the UTC offset AND the timezone in brackets, as shown below.
The timezone (PDT)
is troublesome as my code works until then. datestring1
is converted correctly, but datestring2
isn't.
import time
import datetime
datestring1 = "Mon, 14 May 2001 16:39:00 -0700"
datestring2 = "Mon, 14 May 2001 16:39:00 -0700 (PDT)"
time.mktime(datetime.datetime.strptime(datestring1, "%a, %d %b %Y %H:%M:%S %z").timetuple())
time.mktime(datetime.datetime.strptime(datestring2, "%a, %d %b %Y %H:%M:%S %z (%Z)").timetuple())
CodePudding user response:
You could use python-dateutil
. Take a look at the answer here: Python strptime() and timezones?
It seems others have also had trouble parsing Timezone names using %Z
.
In your case that would be:
import time
import datetime
from dateutil import parser
datestring1 = "Mon, 14 May 2001 16:39:00 -0700"
datestring2 = "Mon, 14 May 2001 16:39:00 -0700 (PDT)"
print(time.mktime(parser.parse(datestring1).timetuple()))
print(time.mktime(parser.parse(datestring2).timetuple()))