摘要:Mac上的“负面”时间戳工作正常,但在Windows上我无法将它们转换为可用的东西。
详细说明: 我可以在Windows上有一个文件,修改时间是1904:
$ ls -l peter.txt
-rw-r--r-- 1 sync Administ 1 Jan 1 1904 peter.txt
在python中:
>>> import os
>>> ss = os.stat('peter.txt')
>>> ss.st_mtime
-2082816000.0
大。但我无法弄清楚如何将负时间戳转换为日期/时间字符串。在Mac上,此代码工作正常。
>>> datetime.fromtimestamp(-2082816000)
datetime.datetime(1904, 1, 1, 0, 0)
从这里开始,我可以在格式化方面做任何我想做的事。
但是在Windows上失败了:
>>> datetime.fromtimestamp(-2082816000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform localtime()/gmtime() function
尝试其他任何我能想到的事都失败了:
>>> time.gmtime(-2082816000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: (22, 'Invalid argument')
精彩的python-dateutil包似乎没有这个功能。我看过时间,日历和日期时间模块。有什么帮助吗?
答案 0 :(得分:9)
>>> datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)
datetime.datetime(1904, 1, 1, 8, 0)
答案 1 :(得分:1)
使用Ignacio的想法,此函数会将任何时间戳转换为正确的天真日期时间对象:
def convert_timestamp_to_datetime(timestamp):
import datetime as dt
if timestamp >=0:
return dt.datetime.fromtimestamp(timestamp)
else:
return dt.datetime(1970, 1, 1) + dt.timedelta(seconds=int(timestamp))