Ignat Talitskikh
Ignat Talitskikh

Reputation: 33

Converting Unix timestamp to date time - different results for JS and Python

I have sqlite log file where date is in timestamp.

The conversion with JS by following function gives the correct result

var unixTsToDate = function (UNIX_Timestamp){
var date = new Date(UNIX_Timestamp / 1000);
return date;
};

unixTsToDate (1615370972685000) = Wed Mar 10 2021 11:09:32 GMT+0100

Now I'm trying to to the same with Python 3.9 and it aborts with Error

import datetime
print(datetime.datetime.utcfromtimestamp(1615370972685000))

result:
print(datetime.datetime.utcfromtimestamp(1615370972685000))
OSError: [Errno 22] Invalid argument

The number seems too big for the function. Tried with /1000 (found in internet that could be different timestamps with milliseconds and without), no result

What could be a solution for Python in the case?

Upvotes: 2

Views: 862

Answers (2)

Weilory
Weilory

Reputation: 3111

Python

round(time.mktime(datetime.timetuple())
# in seconds, if you want to deliver this to frontend, multiply by 1000

Upvotes: 0

tromgy
tromgy

Reputation: 5823

Your timestamp value has microsecond resolution.

51 years (since epoch) * 365 * 24 * 3600 will give roughly 1.6 billion seconds. Your value has additional 6 digits.

So in Python divide by 1000000 instead of 1000.

Upvotes: 1

Related Questions