What does time.sleep(10) in python do during daylight savings time?

1k views Asked by At

If it's 5 seconds before setting the time forward an hour, will time.sleep(10) sleep for 10 seconds, or five seconds? (after five seconds, the time is more than ten seconds from the start).

If it's 5 seconds before setting the time backwards an hour, time.sleep(10) sleep for ten seconds, or for an hour and ten seconds? (it takes an extra hour for the current time to be more than ten seconds from the start time, at least by the clock)

And for completeness, what does sleep do for leap seconds, like we just had?

Are there any times that time.sleep would not be expected to do what is requested?

I'm still on python 2.7.

3

There are 3 answers

0
Moinuddin Quadri On BEST ANSWER

As the time.sleep() document says:

Suspend execution of the current thread for the given number of seconds.

time.sleep() is independent of the time-zone, or your system time. It suspends execution of current thread for the amount of seconds specified while making the call to it.

Answer to your question "Are there any times that time.sleep would not be expected to do what is requested?" is also available in document:

The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine.

But this is changed in version 3.5, and function sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).

Note: The suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system

0
hiro protagonist On

time.sleep(10) does not look at 'wall time'; it counts 10 seconds in 'CPU time'. (there is a discussion about the accuracy of this here: How accurate is python's time.sleep()?)

0
Willis Blackburn On

Most computers track time in terms of seconds, or milliseconds, since an "epoch," which is usually January 1, 1970 UTC.

Setting the time zone to something other than UTC doesn't actually change the system clock. The system clock continues to run in UTC. Instead the computer simply remembers that you, the user, would like to see the time in some particular time zone, and converts the UTC system time to your preferred time zone whenever it's needed.

So the reason the sleep function won't be affected by a daylight savings time change is that the computer calculates the wake-up time relative to the system clock, which is always UTC.