无法将日期转换为 UTC

Can't make sense of date conversion to UTC

我有一个包含 UTC 日期和时间的字符串(不是字符串的一部分,但我知道它是 UTC)。因此,我使用以下代码创建了一个感知日期时间对象:

>>> import datetime
>>> import pytz
>>> mystr = '01/09/2018 00:15:00'
>>> start_time = pytz.utc.localize(datetime.datetime.strptime(mystr, '%d/%m/%Y %H:%M:%S'))
>>> start_time
datetime.datetime(2018, 9, 1, 0, 15, tzinfo=<UTC>)
>>> str(start_time)
'2018-09-01 00:15:00+00:00'
>>> start_time.strftime('%s')
'1535757300'

现在一切似乎都很好,但如果我在 shell:

$ TZ=UTC date -d @1535757300
Fri Aug 31 23:15:00 UTC 2018

我不应该得到 Sat Sep 1 00:15:00 UTC 2018 吗(即,我开始的同一天)?

您需要使用以下内容:

int((start_time - datetime.datetime(1970,1,1)).total_seconds())

因为您使用的是 strftime,它引用的是您的系统时间,该时间可能在您当地的时区。像上面这样自己计算比较靠谱

编辑:

正如 OP 的后续 post 所述,仅使用 start_time.timestamp() 更容易,但这仅适用于 Python 3.3* 及更高版本。

经过更多尝试,https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior 官方文档中列出的格式说明符似乎不支持 %s。相反,我使用 timestamp() 方法得到了正确的结果:

>>> start_time.timestamp()
1535760900.0