I try:
ts = -216345600000
datetime.datetime.fromtimestamp(ts/1000)
ValueError: timestamp out of range for platform localtime()/gmti
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).