Home > Software design >  python Incorrect date when converting unix time to utc time
python Incorrect date when converting unix time to utc time

Time:10-24

i would like to convert unix timestamp to utc time. i have to convert it using the code below, but each time i get an incorrect result. online date converter returns correct result. how to convert a date to count the number of hours between two periods?

import datetime

print(datetime.datetime.fromtimestamp(1633438809404))
ValueError: year 53731 is out of range


import time

epoch = 1633438809404
time_obj = time.localtime(int(epoch))
print(time_obj)

time.struct_time(tm_year=53731, tm_mon=8, tm_mday=13, tm_hour=18, tm_min=36, tm_sec=44, tm_wday=0, tm_yday=225, tm_isdst=0)


import pandas

timestamp = 1633438809404
unix_conversion=pandas.to_datetime(timestamp, unit='ns')
print(str(unix_conversion))

1970-01-01 00:27:13.438809404

CodePudding user response:

The timestamp you've provided (1633438809404) is a timestamp in milliseconds, yes? If so, then divide it by 1000 before providing it to datetime.datetime.fromtimestamp (which expects a timestamp in seconds):

>>> datetime.fromtimestamp(1633438809404/1000)
datetime.datetime(2021, 10, 5, 9, 0, 9, 404000)

or, when using pandas.to_datetime, ensure you use unit='ms':

>>> timestamp = 1633438809404
>>> unix_conversion=pandas.to_datetime(timestamp, unit='ms')
>>> unix_conversion
Timestamp('2021-10-05 13:00:09.404000')
  • Related