How do I convert a datetime string in local time to a string in UTC time?
I\'m sure I\'ve done this before, but can\'t find it and SO will hopefull
Briefly, to convert any datetime
date to UTC time:
from datetime import datetime
def to_utc(date):
return datetime(*date.utctimetuple()[:6])
Let's explain with an example. First, we need to create a datetime
from the string:
>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")
Then, we can call the function:
>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)
Step by step how the function works:
>>> date.utctimetuple()
time.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)
>>> date.utctimetuple()[:6]
(2011, 2, 12, 1, 33, 54)
>>> datetime(*date.utctimetuple()[:6])
datetime.datetime(2011, 2, 12, 1, 33, 54)