将以毫秒为单位的13位unixtime转换为python中的时间戳 [英] converting 13-digit unixtime in ms to timestamp in python

查看:237
本文介绍了将以毫秒为单位的13位unixtime转换为python中的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以毫秒为单位的13位Unix时间转换为时间戳:

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

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

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

我已经尝试过以下链接中的以下代码
但是我认为这是10位Unix时间,而我是13位Unix时间。因此,

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'

但这是错误:

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


推荐答案

您有毫秒级的时间戳,因此请先将其除以 1000 ,然后将其输入到 datetime.datetime.fromtimestamp() 用于本地时区(或传递目标时区的 datetime.tzinfo 作为第二个参数)或 datetime.datetime.utcfromtimestamp() 。最后,使用 datetime.datetime.strftime( ) 将其转换为所需格式的字符串。

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

这篇关于将以毫秒为单位的13位unixtime转换为python中的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆