2

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)

3
  • The issue might be that %H and %S should be zero-padded, and the numbers you are testing are not. Commented Oct 3, 2016 at 12:27
  • That will not fix my problem, however thank you. Commented Oct 3, 2016 at 12:28
  • 3
    Also, your test code does not raise an error for me. I get -2207311257.0 printed to the console. Commented Oct 3, 2016 at 12:29

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.