6

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

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
MarcoBuster
  • 1,145
  • 1
  • 13
  • 21

1 Answers1

14

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'

Callidior
  • 2,899
  • 2
  • 18
  • 28