1

While working with Python's time module I got this error:

OverflowError: mktime argument out of range

What I have found concerning this was that the time might be outside of the epoch and therefore can not be displayed on my windows enviroment.

However the code tested by me is:

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

How can I avoid this? My goal is to get the difference between to points of time on the same day. (I won't get any information about month or year)

kfb
  • 6,252
  • 6
  • 40
  • 51
WodkaRHR
  • 165
  • 3
  • 10

1 Answers1

2

You problem is that the timetuple created by time.strptime(s, "%d %H %M %S ") is:

(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)

...and the documentation for time.mktime() states (emphasis mine):

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.

So this suggests that 1900 is too early to convert. On my system (Win 7), I also get an error, but if I change your code to include a recent year:

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

I get no error, but if I change the year to 1950, I get OverflowError.

So the solution is to include a year in your string, that time.mktime() can convert.

SiHa
  • 7,830
  • 13
  • 34
  • 43