问题
What does python time
and datetime
module return on the leap second?
What will I get when we are at 23:59:60.5 if I call:
time.time()
datetime.datetime.utcnow()
datetime.datetime.now(pytz.utc)
Also, any difference between py2.7 and py3?
Why it is confusing (at least for me):
From the datetime docs I see:
Unlike the time module, the datetime module does not support leap seconds.
On the time docs I see there is "support" for leap seconds when parsing with strptime
. But there is no comment about time.time()
.
I see that using time
I get:
>>> time.mktime(time.strptime('2016-06-30T23:59:59', "%Y-%m-%dT%H:%M:%S"))
1467327599.0
>>> time.mktime(time.strptime('2016-06-30T23:59:60', "%Y-%m-%dT%H:%M:%S"))
1467327600.0
>>> time.mktime(time.strptime('2016-07-01T00:00:00', "%Y-%m-%dT%H:%M:%S"))
1467327600.0
And datetime
just blows up:
>>> dt.datetime.strptime('2016-06-30T23:59:60', "%Y-%m-%dT%H:%M:%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: second must be in 0..59
Then what will I get at that exact time (in the middle of the leap second)?
I have read about rubber times, clocks slowing down, repeating seconds, and all kind of crazy ideas, but what should I expect on python?
Note: In case you wonder if I don't have anything better to do that care about it, a leap second is approaching!!!!
回答1:
Leap seconds are occasionally manually scheduled. Currently, computer clocks have no facility to honour leap seconds; there is no standard to tell them up-front to insert one. Instead, computer clocks periodically re-synch their time keeping via the NTP protocol and adjust automatically after the leap second has been inserted.
Next, computer clocks usually report the time as seconds since the epoch. It'd be up to the datetime
module to adjust its accounting when converting that second count to include leap seconds. It doesn't do this at present. time.time()
will just report a time count based on the seconds-since-the-epoch.
So, nothing different will happen when the leap second is officially in effect, other than that your computer clock will be 1 second of for a little while.
The issues with datetime
only cover representing a leap second timestamp, which it can't. It won't be asked to do so anyway.
回答2:
Python's mktime
behavior here is pretty much just inherited from C's, which is specified by POSIX. The spec isn't as simple as you might think, and the reality is even more complicated.
I think this article is a good introduction to the various issues: The Unix leap second mess
The datetime
module, as you observed, just acts like there is no such thing as a leap second.
来源:https://stackoverflow.com/questions/39686553/what-does-python-return-on-the-leap-second