简而言之,将任何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)