简体   繁体   中英

Convert python timezone aware datetime string to utc time

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.

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>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM