Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert UnixTimeStamp (with Minus) to Date

How i can convert UnixTimeStamp like -266086800 (with Minus) to date

>>> datetime.fromtimestamp('-266086800').strftime("%A, %B %d, %Y %I:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)

UPDATE

After fixing bug where timestamp was passed as a string

datetime.datetime.fromtimestamp(-266086800)

another error is presented (on Windows)

OSError: [Errno 22] Invalid argument
like image 815
Mehdi SH Avatar asked Jun 22 '26 11:06

Mehdi SH


1 Answers

After changing the parameter from a string to an integer, success is platform dependent. fromtimestamp uses the C localtime function and from classmethod datetime.fromtimestamp(timestamp, tz=None): It’s common for this to be restricted to years in 1970 through 2038.

Negative Unix timestamps mean time before Jan 1, 1970. You could get the time at timestamp 0 and then add a python timedelta object for the time. Now the calculation is done in python, removing that restriction.

>>> import datetime
>>> datetime.datetime.fromtimestamp(0) + datetime.timedelta(seconds=-266086800)
datetime.datetime(1961, 7, 27, 0, 0)
like image 116
tdelaney Avatar answered Jun 24 '26 00:06

tdelaney