Skip to content

gh-81708: Fixing the "Invalid argument" bug on datetime.timestamp() #15498

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions Lib/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1889,10 +1889,13 @@ def local(u):
# We found one solution, but it may not be the one we need.
# Look for an earlier solution (if `fold` is 0), or a
# later one (if `fold` is 1).
u2 = u1 + (-max_fold_seconds, max_fold_seconds)[self.fold]
b = local(u2) - u2
if a == b:
if u1 < max_fold_seconds:
return u1
else:
u2 = u1 + (-max_fold_seconds, max_fold_seconds)[self.fold]
b = local(u2) - u2
if a == b:
return u1
else:
b = t1 - u1
assert a != b
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:meth:`datetime.datetime.timestamp` with dates near The Unix Epoch no longer
raises ``OSError: [Errno 22] Invalid argument`` on Windows.
17 changes: 17 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# datetime.timestamp() fails when the 'datetime' is close to the Epoch
# Here is the test runs on win10 os, python3.7-3.9. My time is 'utc +8'

from datetime import datetime

def test(year,month,day,hour=0,minute=0,second=0):
t = datetime(year,month,day,hour)
try:
print(t.timestamp())
except Exception as e:
print(e)
return

test(1970,1,1)
test(1970,1,1,8)
test(1970,1,2,7,59,59)
test(1970,1,2,8) # this time is just okay