Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from UNIX timestamp (with milliseconds) to HH:MM:SS in Python [duplicate]

I need to convert UNIX timestamp in miliseconds to HH:MM:SS. If I try to do this:

import datetime
var = 1458365220000
temp = datetime.datetime.fromtimestamp(var).strftime('%H:%M:%S')
print (temp)

It's doesn't works, and the error I am getting is is:

OSError: [Errno 22] Invalid argument

like image 684
MarcoBuster Avatar asked Mar 19 '16 15:03

MarcoBuster


1 Answers

The error is due to the milliseconds which push the number out of the range of 32-bit integers. datetime.datetime.fromtimestamp expects the first argument to be the number of seconds since the begin of the UNIX epoch. However, it is capable of handling fractions of a second given as floating point number. Thus, all you have to do is to divide your timestamp by 1000:

import datetime
var = 1458365220000
temp = datetime.datetime.fromtimestamp(var / 1000).strftime('%H:%M:%S')
print (temp)

If you also want to include the milliseconds in your formatted string, use the following format: '%H:%M:%S.%f'

like image 101
Callidior Avatar answered Nov 07 '22 21:11

Callidior