首页 > 解决方案 > 在 Python 中将纪元时间转换为本地时间的困惑

问题描述

我有纪元时间,需要将其转换为当地时间(美国/太平洋)。pandas to_datetime()我使用函数和得到以下结果datetime.datetime.fromtimestamp()

datetime.datetime.fromtimestamp(1554782410.0370002)
Out[704]: datetime.datetime(2019, 4, 8, 21, 0, 10, 37000)

pd.to_datetime(1554782410.0370002, unit='s')
Out[705]: Timestamp('2019-04-09 04:00:10.037000179')

请注意,两个输出之间的时间差为 7:00 小时。我该如何调和两者?

任何帮助将不胜感激。

谢谢。

标签: pythonpandastime

解决方案


I prefer to define in UTC (tz aware) then convert:

pd.to_datetime(1554782410.0370002, unit='s', utc=True).tz_convert('US/Pacific')

The obvious thing you dont want to do manually subtract hours. If you happen to move, or your code runs on a server in another timezone, it will fail if you manually subtract off the hours. In short: use a package/api for timezone management if you want timezone-aware times.


推荐阅读