Search code examples
pythonpython-3.xdatetimeepoch

Why is Datetime's `.timestamp()` method returning `OSError: [Errno 22] Invalid argument`?


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.


Solution

  • 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