Parsing Python中从历元时间戳转换的混淆
我有以下简单的脚本(使用Python3.4) 1) 执行Parsing Python中从历元时间戳转换的混淆,parsing,datetime,python-3.4,epoch,Parsing,Datetime,Python 3.4,Epoch,我有以下简单的脚本(使用Python3.4) 1) 执行datetime.datetime.fromtimestamp(int(d1)).strftime(“%c”)时,会引发以下错误: >>> datetime.datetime.fromtimestamp(int(d1)).strftime('%c') Traceback (most recent call last): File "<stdin>", line 1, in <module> Ov
datetime.datetime.fromtimestamp(int(d1)).strftime(“%c”)
时,会引发以下错误:
>>> datetime.datetime.fromtimestamp(int(d1)).strftime('%c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: timestamp out of range for platform time_t
3) 但是,如果我想使用parse(d2)
我会得到一个错误
>>> parse(d2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/dateutil/parser.py", line 1168, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/dateutil/parser.py", line 578, in parse
if cday > monthrange(cyear, cmonth)[1]:
File "/usr/lib/python3.4/calendar.py", line 121, in monthrange
day1 = weekday(year, month, 1)
File "/usr/lib/python3.4/calendar.py", line 113, in weekday
return datetime.date(year, month, day).weekday()
ValueError: year is out of range
5) 最后,如果您在中使用d1
,您将正确获得预期日期
为什么会这样?我只是想通过使用parse()
来检查字符串是否是日期时间,但即使epoch字符串很好(至少是d2),也不起作用
另一方面,为什么d1不如epoch好
谢谢
卢卡斯到现在为止,你可能已经明白了这一点,但不管怎样,事情还是发生了:
parser的parse
函数无法解析Unix时间-。
这就是答案3和4
现在转到1和2。无法解析d1的原因是因为它不是Unix时间。Unix时间定义为自1970年1月1日星期四00:00:00协调世界时(UTC)以来经过的秒数减去自那时起发生的闰秒数(感谢维基百科!)。如果要包括指定毫秒,请将它们添加到小数点后,如下所示:
d1 = "1490917274.299"
解析时,请确保使用float
而不是int
>>> parse(d2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/dateutil/parser.py", line 1168, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/dateutil/parser.py", line 578, in parse
if cday > monthrange(cyear, cmonth)[1]:
File "/usr/lib/python3.4/calendar.py", line 121, in monthrange
day1 = weekday(year, month, 1)
File "/usr/lib/python3.4/calendar.py", line 113, in weekday
return datetime.date(year, month, day).weekday()
ValueError: year is out of range
>>> parse(d1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/dateutil/parser.py", line 1168, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/dateutil/parser.py", line 578, in parse
if cday > monthrange(cyear, cmonth)[1]:
File "/usr/lib/python3.4/calendar.py", line 121, in monthrange
day1 = weekday(year, month, 1)
File "/usr/lib/python3.4/calendar.py", line 113, in weekday
return datetime.date(year, month, day).weekday()
OverflowError: Python int too large to convert to C long
d1 = "1490917274.299"
datetime.datetime.fromtimestamp(float(d1)).strftime('%c')