如何区分 UTC 日期时间和 Python 中的 utcnow

How to get the difference between a datetime in UTC and utcnow in Python

我有一个字符串形式的日期时间 (2016-12-31 23:59),从中我知道它是在 UTC 中定义的。我现在想使用 Python 获取时间增量。我正在执行此操作的机器通常处于 CEST 时区 (Europe/Amsterdam),但情况可能并非总是如此,因此我不想在代码中对这个时区进行硬编码。

对于本地时区,这会很有效:

date_str = '2016-12-31 23:59'
print datetime.now() - datetime.strptime(date_str, '%Y-%m-%d %H:%M')

虽然这显然是不正确的,但将其更改为使用 utcnow() 也不正确:

print datetime.utcnow() - datetime.strptime(date_str, '%Y-%m-%d %H:%M')

这不能正常工作,因为现在由 strptime 产生的日期时间在机器的时区中,此代码 运行 打开,而 utcnow() 在 UTC 中。

我找到了 this SO answer,但前提是您知道代码所在机器的时区 运行,而我不知道。

有没有一种方法可以将 UTC 时区添加到从 datetime.strptime() 获得的 datetime 对象中,以便我可以将其与 utcnow() 进行比较?欢迎所有提示

你的代码实际上没问题。你的错误在于这个假设:"the datetime resulting from strptime is in the timezone of the machine this code is running on."

datetime.strptime(date_str, '%Y-%m-%d %H:%M') 将生成一个 naive 日期时间,表示您所说的 UTC 时间。

datetime.utcnow() 将生成一个 naive 日期时间,表示 UTC 中的当前时间。

所以差异是准确的。