-1

I'm trying to convert the datetime object to timestamp so that I can save the time stamp to a json file and later I can convert that timestamp to datetime object.

This worked fine until I set the year greater than 1970, But when decreased the year an exception got raised saying OSError: [Errno 22] Invalid argument

import datetime
cd = datetime.datetime.strptime("1965-12-25", "%Y-%m-%d")
datetime.datetime.timestamp(cd) # this line gives error
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
OSError: [Errno 22] Invalid argument

I'm using windows 10 OS. Is there any exception or other way to convert the datetime to timestamp?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

1 Answers1

1

you could calculate the negative timestamp as a timedelta from the epoch (1970-1-1):

import datetime
cd = datetime.datetime.strptime("1965-12-25", "%Y-%m-%d")

ts = (cd-datetime.datetime(1970,1,1)).total_seconds()

print(ts)
>>> -126835200.0

...and the other way round would be something like

dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=ts)
print(dt)
>>> 1965-12-25 00:00:00

related:

FObersteiner
  • 22,500
  • 8
  • 42
  • 72