Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python timezone aware datetime string to utc time

Tags:

python

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.

like image 352
user1050619 Avatar asked Feb 12 '26 23:02

user1050619


1 Answers

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>)
like image 63
PdevG Avatar answered Feb 14 '26 12:02

PdevG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!