8

I make use of the .timestamp() function twice in my code, to convert datetime objects into epoch time. The first call to .timestamp() looks like this:

import datetime    
origin_epoch = origin.timestamp()

the contents of the variables origin and origin_epoch are:

Screenshot of Visual Studio Code's debugger for variables.

Meanwhile, if I try to call the same method elsewhere in my code

import datetime
print(datetime.datetime(1900, 1, 1, 19, 6, 28).timestamp())

Then I get the following error: OSError: [Errno 22] Invalid argument Why is this?

edit: this error occurred on Windows 10.

Community
  • 1
  • 1
David
  • 606
  • 9
  • 19

3 Answers3

7

This appears to be a known issue which has been supposedly fixed, but I haven't checked. On my Windows (Windows 10, GMT+2) any date before 1970-01-02 02:00:00 or beyond 3001-01-19 07:59:59 will give an OSError when timestamp() is called.

However, this does not happen to offset-aware datetime, instead, a call to timestamp() gets computed as (from the docs):

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

So if you work with offset-naive datetimes, you can simply use:

(dt - datetime(1970, 1, 1)).total_seconds()
Yuval
  • 3,207
  • 32
  • 45
6

The year 1900 was before the beginning of the UNIX epoch, which was in 1970, so the number of seconds returned by timestamp must be negative. To be precise, should be negative, but apparently, not in your case. Looks like your OS just treats dates before the beginning of the UNIX epoch as errors.

This works fine for me on macOS, though:

>>> datetime.datetime(1900, 1, 1, 19, 6, 28).timestamp()
-2208929029.0
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Wow, I never would have guessed this. Thanks so much! It's funny because, if you don't specify a year, the default year in the datetime module is 1900. So on windows, whenever you run `timestamp()` on a datetime object with the default year, the program will crash with this "Errno 22" – David Dec 05 '19 at 17:34
  • 1
    @David, [this question](https://stackoverflow.com/q/54470408/4354477) may also be helpful – ForceBru Dec 05 '19 at 17:44
-1

I replaced the year value with 2000 and now it works fine.

time_sec = datetime.strptime("00:00:13.345", "%H:%M:%S.%f")
print(time_sec.replace(year=2000).timestamp())
Andrew Ryan
  • 1,489
  • 3
  • 15
  • 21