3

I have a Python datetime string that is timezone aware and need to convert it to UTC timestamp.

'2016-07-15T10:00:00-06:00'

Most of the SO links talks about getting the current datetime in UTC but not on converting the given datetime to UTC.

user1050619
  • 19,822
  • 85
  • 237
  • 413

1 Answers1

1

Hi this was a bit tricky, but here is my, probably far from perfect, answer:

[IN]
import datetime
import pytz
date_str = '2016-07-15T10:00:00-06:00'
# Have to get rid of that bothersome final colon for %z to work
datetime_object = datetime.datetime.strptime(date_str[:-3] + date_str[-2:], 
'%Y-%m-%dT%H:%M:%S%z')
datetime_object.astimezone(pytz.utc)
[OUT]
datetime.datetime(2016, 7, 15, 16, 0, tzinfo=<UTC>)
PdevG
  • 3,427
  • 15
  • 30
  • `%z` support isn't universal, see http://stackoverflow.com/questions/26165659/python-timezone-z-directive-for-datetime-strptime-not-available. And it's a colon, not a semicolon. – Mark Ransom Jul 19 '16 at 19:10
  • Fair point, from 3.2 it should be implemented. Don't know which version op is using! – PdevG Jul 19 '16 at 20:58