Python fromtimestamp() 方法不一致

标签 python macos datetime pycharm

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

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

# 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

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

格林威治标准时间:2016 年 9 月 22 日星期四 16:07:14 GMT

您的时区:2016 年 9 月 22 日上午 11:07:14 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是时区的完整列表。尝试一下看看。

关于Python fromtimestamp() 方法不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39775408/

相关文章:

mysql - 在mySQL中将日期时间转换为unix时间戳

python - 我无法使用 Pyinstaller 打包我的程序,因为我安装了 enum34,无法卸载,因为已使用的模块需要它。有什么建议么?

python - 在 pandas/ipython 中选择特定的 excel 行进行分析?

ruby - 通过 RVM `C compiler cannot create executables` 安装 Ruby 时运行配置时出错

macos - -bash : pylint: command not found

windows - 如何在启动时同步计算机的时钟?

php - mySQL 日期列搞砸了

python - 使用 __del__ 停止 python 线程

python - 外部函数中的嵌套函数更改变量不起作用

带有集成标题栏和工具栏的 macOS 窗口?