Skip to content
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

Datetime Issue in Windows #184

Open
ericspod opened this issue May 24, 2021 · 1 comment
Open

Datetime Issue in Windows #184

ericspod opened this issue May 24, 2021 · 1 comment

Comments

@ericspod
Copy link
Member

Using datetime.datetime produces objects whose timestamp() value is not valid under Windows, at least insofar as Python calculates it. To replicate:

import datetime

dt=datetime.datetime(1970,1,2)
print(dt.timestamp())  # valid

dt=datetime.datetime(1969,1,2)
print(dt.timestamp())  # raises OSError: [Errno 22] Invalid argument

dt_delta=(dt - datetime.datetime(1970, 1, 1))
print(dt.total_seconds())  # works to produce the correct timestamp

What's going on here is the default datetime object doesn't handle timestamps correctly for dates before Jan 2 1970 and after Jan 19 3001. By subtracting the epoch (Jan 1 1970) from a datetime this produces a timedelta object whose total_seconds method returns the timestamp that is expected. A routine is required to get the correct timestamp that will be portable across platforms:

def timestamp(dt):
    return (dt - datetime.datetime(1970, 1, 1)).total_seconds()

This should be used in place of calling the datetime.datetime.timestamp method. However, datetime.datetime.fromtimestamp will not work with these values, a function to do this needed as well:

def fromtimestamp(ts):
    return datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=ts)
@ericspod
Copy link
Member Author

We do need to change our tests to cover the three platforms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant