【问题标题】:Python epoch - datetime conversion bug?Python epoch - 日期时间转换错误?
【发布时间】:2018-12-23 08:40:52
【问题描述】:

所以我有以下代码:

import pytz
from datetime import datetime


tz = pytz.timezone('Asia/Singapore')

original_time = tz.localize(datetime.now())
original_epoch = original_time.timestamp()
converted_dt = tz.localize(datetime.utcfromtimestamp(original_epoch))
converted_epoch = converted_dt.timestamp()

print('{}\t\t{}'.format(original_time, original_epoch))
print('{}\t\t{}'.format(converted_dt, converted_epoch))

然后吐出来

# Original Time                         Original Epoch
2018-07-16 02:17:41.583510+08:00        1531678661.58351
2018-07-15 18:17:41.583510+08:00        1531649861.58351
# Converted Time                        Converted Epoch

这是一个 Python 错误还是我只是遗漏了什么?无论哪种方式,我怎样才能将日期时间转换为纪元并返回,并确信我回到了正确的时间?

【问题讨论】:

    标签: python python-3.x python-3.6 pytz


    【解决方案1】:

    tz.localize() 不对给定的datetime 执行任何时区调整;它只是将其tzinfo 设置为给定的时区。对于您使用的时间戳,这意味着 tz.localtime() 执行以下操作:

     datetime.now()                           ->  tz.localize(datetime.now())
     2018-07-16 02:17:41.583510                   2018-07-16 02:17:41.583510+08:00
    
     datetime.utcfromtimestamp(original_epoch) -> tz.localize(datetime.utcfromtimestamp(original_epoch))
     2018-07-15 18:17:41.583510                -> 2018-07-15 18:17:41.583510+08:00
    

    请注意,时间不会改变;只有时区偏移量。因为tz.localize() 的输入是两个不同的初始时间,所以您会得到两个不同的感知时间。

    从 UNIX 时间戳和时区构造 datetime 的正确方法是使用带有两个参数的 datetime.fromtimestamp()

    >>> print(datetime.fromtimestamp(1531678661.58351, pytz.timezone('Asia/Singapore')))
    2018-07-16 02:17:41.583510+08:00
    

    【讨论】:

    • 感谢 Jwodder!整晚都想弄清楚。
    猜你喜欢
    • 2018-07-25
    • 2020-06-15
    • 2012-04-01
    • 2011-10-09
    • 2017-03-23
    • 2018-01-21
    • 1970-01-01
    • 2014-06-10
    • 2015-07-03
    相关资源
    最近更新 更多