Convert pymongo millisecond to different format

Viewed 34

I'm attempting to convert 1614100501543 of type 'bson.int64.Int64' to a formatted date using datetime:

The below code:

print(results[0][0] , type(results[0][0]))

print(datetime.utcfromtimestamp(results[0][0]).strftime('%Y-%m-%d %H:%M:%S'))

returns :

1614100501543 <class 'bson.int64.Int64'>
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-142-97decf382ca6> in <module>
      1 print(results[0][0] , type(results[0][0]))
      2 
----> 3 print(datetime.utcfromtimestamp(results[0][0]).strftime('%Y-%m-%d %H:%M:%S'))

ValueError: year 53118 is out of range

How to set the DateTime correctly to allow correct conversion?

1 Answers

utcfromtimestamp() expects an epoch in seconds, but you are supplying an epoch in milliseconds.

Divide the number by 1000 and it will work.

x = 1614100501543
d = datetime.utcfromtimestamp(x / 1000)
print(d)

prints

2021-02-23 17:15:01.543000
Related