2016-10-03 163 views
0

虽然与Python的time模块工作,我得到这个错误:Python的时间错误:mktime溢出

OverflowError: mktime argument out of range

我已经找到关于这,时间可能是划时代的外面,因此无法显示我的窗户环境。

但是通过我测试的代码是:

import time 
s = "20 3 59 3 " 
t = time.mktime(time.strptime(s, "%d %H %M %S ")) 
print(t) 

我怎样才能避免这种情况?我的目标是在同一天获得不同时间点之间的差异。 (我不会得到约一个月或一年的任何信息)

+0

问题可能是'%H'和'%S'应该填零,并且您正在测试的数字不是。 – elethan

+0

这不会解决我的问题,但是,谢谢。 – WodkaRHR

+3

此外,您的测试代码不会为我提出错误。我把'-2207311257.0'打印到控制台上。 – elethan

回答

0

您的问题是,由time.strptime(s, "%d %H %M %S ")创建的timetuple是:

(tm_year=1900, tm_mon=1, tm_mday=20, tm_hour=3, tm_min=59, tm_sec=3, tm_wday=5, tm_yday=20, tm_isdst=-1) 

...和time.mktime()国家(重点煤矿)的文档:

time.mktime(t) This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

所以这表明1900为时尚早。在我的系统(Win 7的),我也得到一个错误,但如果我改变你的代码,包括最近的一年:

>>> s = "1970 20 3 59 3 " 
>>> t = time.mktime(time.strptime(s, "%Y %d %H %M %S ")) 
>>> print t 
1655943.0 

我没有错误,但如果我改变了今年1950,我得到OverflowError

因此,解决方案是在您的字符串中包含一年,即time.mktime()可以转换。