【问题标题】:Python's datetime.datetime.timestamp() is inaccurate/inconsistent with DiscordPython 的 datetime.datetime.timestamp() 不准确/与 Discord 不一致
【发布时间】:2021-12-25 19:41:10
【问题描述】:

原始问题

我最近正在研究远在过去的日期时间,比如公元 200 年。使用datetime.datetime(200, 1, 1, 0, 0, 0).timestamp(),我得到了-55855785600 的时间戳。然而,当我使用在线时间戳生成器时,他们给了我一个-55855813002 的时间戳。

当我将两个时间戳都粘贴到 Discord 中时,它显示:

Datetime Result Result (Adjusted to UTC+0)
My timestamp - <t:-55855785600:T> 7:36:42 AM 23:36:42 AM the last day
Their timestamp - <t:-55855813002:T> 8:00:00 AM 0:00:00 AM

(我住在 UTC+8)

这种 23 分 18 秒的误差也发生在公元 161 年的日期时间中,所以我认为闰年没有问题。

我的代码有问题吗? UNIX Epoch Times 是否有多个系统导致了这个事件?任何帮助,将不胜感激。谢谢!

编辑

我刚刚查看了时间戳生成器网站的源代码,发现他们使用的是 moment.js。我试过 moment.js' moment().unix() 并且时间戳是准确的。 Python 和 Javascript 时间戳计算器有什么区别吗?

【问题讨论】:

  • 您需要设置时区才能获得可比较的结果。如果不这样做,Python 的原始日期时间将是 本地时间(您的操作系统设置),而不是 UTC。

标签: python datetime timestamp momentjs


【解决方案1】:

问题是你当地的时区,你应该依赖UTC,因为有些计算是错误的,这里你可以看一些例子:

from datetime import datetime
from datetime import timezone


if __name__ == '__main__':
    years = [2000, 1950, 1894, 1893, 200]
    for year in years:
        dt1 = datetime(year, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
        dt2 = datetime(year, 1, 1, 0, 0, 0)
        diff = dt2.timestamp() - dt1.timestamp()
        print(f"Year: {year}")
        print(f"{dt1.timestamp()}   {dt1.strftime('%d.%m.%Y %H:%M:%S')}")
        print(f"{dt2.timestamp()}   {dt2.strftime('%d.%m.%Y %H:%M:%S')}")
        print(f"dif: {diff}")
        print()

然后输出:

Year: 2000
946684800.0   01.01.2000 00:00:00
946681200.0   01.01.2000 00:00:00
dif: -3600.0

Year: 1950
-631152000.0   01.01.1950 00:00:00
-631155600.0   01.01.1950 00:00:00
dif: -3600.0

Year: 1894
-2398291200.0   01.01.1894 00:00:00
-2398294800.0   01.01.1894 00:00:00
dif: -3600.0

Year: 1893
-2429827200.0   01.01.1893 00:00:00
-2429830408.0   01.01.1893 00:00:00
dif: -3208.0

Year: 200
-55855785600.0   01.01.200 00:00:00
-55855788808.0   01.01.200 00:00:00
dif: -3208.0

这里的转折点是 1893/1894(对我来说)。 这些错误是已知的(herehere

【讨论】:

  • 我怀疑你本地时间的UTC偏移量是一小时,并且1894年之前没有时区规则定义,所以它回退到LMT?
  • 谢谢!我只是用了类似的方法,发现我的转折点是1904/1905。不幸的是,我尝试了您的代码,但没有帮助。不过感谢您的贡献!
  • 您的问题到底是什么? -55855785600 是您在 UTC 中搜索日期的正确值。因此,如果您尝试将日期作为时间戳在线获取,您将获得这些数字(如果您指定 UTC)。如果您不能指定 utc,在线计算器会为您提供当地时间,因此您有这个差距,因此如果您在 date_to_timestamp 上指定 utc 但在 timestamp_to_date 上没有指定 utc,您会在线获得不同的值。我尝试使用 epochconverter.comtimestamp.online
  • 不幸的是,这不是 Discord 的情况。
猜你喜欢
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多