Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting 13-digit unixtime in ms to timestamp in python

I want to convert 13-digit Unix-time in milliseconds to the timestamp :

"1523126888080"==>> %Y-%m-%d %H:%M:%S

I have tried the following code from this link,
But I think this is for 10-digit Unix-time and I am having 13-digit Unix-time. So,

This code is working, But it is giving the wrong results and wrong time:

import time
time.strftime("%D %H:%M", time.localtime(int("1523126888080".strip()[0:9])))

Output: '1974-10-30 02:34:48'
Expected: '2018-04-08 12:18:08'

But this one is giving error:

import time
time.strftime("%D %H:%M", time.localtime(int("1523126888080")))

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
time.strftime("%D %H:%M", time.localtime(int("1523126888080")))
OSError: [Errno 22] Invalid argument
like image 461
The_Anil Avatar asked Apr 07 '18 19:04

The_Anil


People also ask

What is a 13 digit timestamp?

A 13 digit timestamp is used in JavaScript to represent time in milliseconds. In PHP 10 a digit timestamp is used to represent time in seconds.

How do I convert a string to a timestamp in Python?

Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.


2 Answers

You have a millisecond-precise timestamp so first divide it by 1000 then feed it to datetime.datetime.fromtimestamp() for local timezone (or pass datetime.tzinfo of the target timezone as a second argument) or datetime.datetime.utcfromtimestamp() for UTC. Finally, use datetime.datetime.strftime() to turn it into a string of your desired format.

import datetime

timestamp = "1523126888080"
your_dt = datetime.datetime.fromtimestamp(int(timestamp)/1000)  # using the local timezone
print(your_dt.strftime("%Y-%m-%d %H:%M:%S"))  # 2018-04-07 20:48:08, YMMV
like image 148
zwer Avatar answered Oct 24 '22 22:10

zwer


Try dividing 1523126888080 by 1000 to get a valid timestamp.
You should also use %d instead of %D as argument for strftime, i.e:

import time
ts = 1523126888080 / 1000
print(time.strftime("%d %H:%M", time.localtime(ts)))
# 29 21:04
like image 29
Pedro Lobito Avatar answered Oct 24 '22 23:10

Pedro Lobito