【问题标题】:Datetime's timestamp function not matching expected UNIX timeDatetime 的时间戳函数与预期的 UNIX 时间不匹配
【发布时间】:2019-07-22 14:34:34
【问题描述】:

以下

import datetime as dt

dt.datetime(2019, 7, 21).timestamp()

返回

1563663600.0 .

但是,如果我查看https://www.unixtimeconverter.io/list/2019/july,我会看到该日期的预期 Unix 时间是 1563667200。

为什么会出现差异?

【问题讨论】:

  • 您当地的时区是多少? 1563667200UTC 时间戳。
  • 我在寻找 UTC 时间戳。运行 .timestamp() 时我没有指定任何本地时区

标签: python python-3.x posix utc python-datetime


【解决方案1】:

datetime 默认不假定 UTC,因此您需要指定它。

dt.datetime(2019, 7, 21, tzinfo=dt.timezone.utc).timestamp()

1563667200

【讨论】:

  • 此行为/解决方案也专门为 the timestamp method 记录:“注意:没有方法可以直接从代表 UTC 时间的幼稚 datetime 实例获取 POSIX 时间戳。如果您的应用程序使用此约定并且您的系统时区未设置为 UTC,您可以通过提供 tzinfo=timezone.utc"(后跟代码示例)获取 POSIX 时间戳
猜你喜欢
  • 1970-01-01
  • 2017-10-06
  • 2010-12-18
  • 2010-11-19
  • 2018-01-04
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
相关资源
最近更新 更多