开发者

Python | mktime overflow error

I have been search all over the net and couldn't find an appropriate solution for this issue

OverflowError: mktime argument out of range

The code that causes this exception

 t = (1956, 3, 2, 0, 0, 0, 0, 0, 0)
 ser = time.mktime(t)

I would like to know the actual reason for this exception, some say that the date is not in a valid range but it doesn't make any sense to me, and if there's a range what it could be. Is it depends upon the system that we are using. Also would like to know a good solution for th开发者_Go百科is issue.

Thanks.


time.mktime calls the underlying mktime function from the platform's C library. For instance, the above code that you posted works perfectly well for me on Mac OS X, although it returns a negative number as the date is before the Unix epoch. So the reason is that your platform's mktime implementation probably does not support dates before the Unix epoch. You can use Python's datetime module to construct a datetime object corresponding to the above date, subtract it from another datetime object that represents the Unix epoch and use the calculated timedelta object to get the number of seconds since the epoch:

from datetime import datetime
epoch = datetime(1970, 1, 1)
t = datetime(1956, 3, 2)
diff = t-epoch
print diff.days * 24 * 3600 + diff.seconds

Update: if you are using Python 2.7 or above, you could simply use print diff.total_seconds() as noted below in Chad Miller's comment.


python time module

Although this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.

The epoch is the point where the time starts, and is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). To find out what the epoch is on a given platform, look at time.gmtime(0).

https://docs.python.org/3/library/time.html

Windows 10:

>>> time.gmtime(0)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

>>> list((ix for ix in time.gmtime(0)))
[1970, 1, 1, 0, 0, 0, 3, 1, 0]

>>> time.mktime(time.gmtime(0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: mktime argument out of range

The C library function on windows 10 does not support times below a certain value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜