Skip to main content
 首页 » 编程设计

Python fromtimestamp() 方法不一致

2024年10月17日8zdz8207

我正在从 WSO2 DAS 获取数据,其中包含一个 Unix 时间戳。我一直在使用 PyCharm 开发这个网站。我主要在 Windows 10 机器上开发,偶尔在 MAC 上开发,然后部署在 Linux 机器上。

我有一个相当简单的用例,我想从 WSO2 获取日期,将其转换为人类可读的本地时间,并将其显示给用户。 问题 我看到的是在 Windows 和 MAC 机器上使用 Python 转换时间戳的不同结果。

# Convert the millisecond time stamp to seconds 
ts = int(hit['timestamp']) / 1000  
 
# Convert the timestamp to a human readable format 
ts = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 

fromtimestamp() 方法的 python 文档说明如下:

date.fromtimestamp(timestamp) Return the local date corresponding to the POSIX timestamp, such as is returned by time.time(). This may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() function. It’s common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp().

该文档可以在这里找到:https://docs.python.org/2/library/datetime.html

现在这在我的 Windows 机器上完美运行。

Windows 上的第 1 行结果:1474560434.73

将其插入时间戳转换器会导致:

GMT:2016 年 9 月 22 日星期四 16:07:14 GMT

您的时区:9/22/2016,11:07:14 AM GMT-5:00 DST

完美!所以我预计第二行的结果是 2016-09-22 11:07:14。可以看到直接从我的代码中复制:

Windows 上的第 2 行结果:'2016-09-22 11:07:14'

现在是乐趣开始的地方。我的 MAC 上有完全相同的代码,也是从 PyCharm 运行的。运行相同的代码,第一行的结果是:

MAC 上的第 1 行结果:1474560434.73

同上,我们预计时间为 9 月 22 日上午 11:07:14。

MAC 上的第 2 行结果:'2016-09-22 16:07:14'

不好。这是结果,仍然是 UTC。

我已确认两台计算机都设置为我的本地时区。 更奇怪的是,在尝试调试这个问题时,我发现了以下结果:

t = time.localtime() 
u = time.gmtime(time.mktime(t)) 
offset = timegm(t) - timegm(u) 

在我的 MAC 上的终端中运行上述代码会给出正确的本地时间 (UTC-5)、正确的 UTC 时间和 -18000 的偏移量(这是正确的)。但!在我的 MAC 上的 PyCharm 中运行相同的代码给出零偏移量,并显示相同的本地时间和 UTC 时间。

我最初对为什么我的 Windows 机器与 MAC 的结果不同感到困惑,但可以假设这是操作系统的差异。但现在我看到了 MAC 终端与 MAC PyCharm 的差异。我只能假设我的 MAC 机器正在引用正确的时区(这就是它在终端中工作的原因)但是 PyCharm 正在引用其他一些时区位置并认为它是 UTC。

请您参考如下方法:

Python 可能使用来自 OS/shell 环境的 TZ。

PyCharm 似乎使用在 settings.py 文件中找到的 TIME_ZONE。 Here是完整的时区列表。试试看。