I try:
ts = -216345600000
datetime.datetime.fromtimestamp(ts/1000)
ValueError: timestamp out of range for platform localtime()/gmtime() function
I check on epochconverter value : -216345600 its return GMT: Sat, 23 Feb 1963 00:00:00 GMT
How to get the correct result?
For many values, like too far in the past or the future, just feeding the timestamp to fromtimestamp()
will complain with an out of range error. However, you can calculate the date using timedelta()
relative from the epoch.
>>> from datetime import datetime, timedelta
>>> date = datetime(1970, 1, 1) + timedelta(seconds=-216345600)
>>> date
datetime.datetime(1963, 2, 23, 0, 0)
>>> date.strftime('%a, %d %b %Y %H:%M:%S GMT')
'Sat, 23 Feb 1963 00:00:00 GMT'
However, do note that you can't use this to go back to the dinosaur era, since datetime()
still has a min and max value it can support.
>>> datetime(1970, 1, 1) + timedelta(seconds=-62135596800)
datetime.datetime(1, 1, 1, 0, 0)
>>> datetime(1970, 1, 1) + timedelta(seconds=253402300799)
datetime.datetime(9999, 12, 31, 23, 59, 59)
>>> datetime(1970, 1, 1) + timedelta(seconds=253402300800)
Traceback (most recent call last):
File "<pyshell#157>", line 1, in <module>
datetime(1970, 1, 1) + timedelta(seconds=253402300800)
OverflowError: date value out of range
timedelta()
has its limits as well, but with the epoch as a reference point, we haven't come even near reaching them.
>>> timedelta(microseconds=1000000000*86400*10000-1)
datetime.timedelta(9999999, 86399, 999999)
Maybe slightly less related to the problem from the question but may be applicable to those who want to represent full date-time range without any very specific workarounds to limitations of the default datetime
implementation.
I have checked a few libraries and I suggest using:
dateparser
- for parsing date/time stated naturally for a human being and in multitude of languages.
arrow
- drop-in replacement for datetime
without its limitations (e.g. possibility to represent dates before and close to the epoch of 1. year AD).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With