简单地说,要将任何datetime日期转换为UTC时间:
from datetime import datetime
def to_utc(date):
return datetime(*date.utctimetuple()[:6])
让我们用一个例子来解释。首先,我们需要从字符串中创建一个datetime:
>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")
然后,我们可以调用函数:
>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)
函数如何一步步工作:
>>> 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)