python linux时间戳到日期时间和反向

前端之家收集整理的这篇文章主要介绍了python linux时间戳到日期时间和反向前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道如何将日期时间转换为 Linux时间戳13668315
Wed Apr 24 19:25:06 2013 GMT

(13位),并使用python反转.

例如:

Wed Apr 24 19:25:06 2013 GMT


13668315
Wed Apr 24 19:25:06 2013 GMT
Wed Apr 24 19:25:06 2013 GMT13668315
Wed Apr 24 19:25:06 2013 GMT
Wed Apr 24 19:25:06 2013 GMTWed Apr 24 19:25:06 2013 GMT

解决方法

从字符串到时间戳,使用 time.strptime(),将生成的struct_time元组传递给 time.mktime();您的时间戳使用毫秒,而不是UNIX秒作为浮点值,因此您需要乘以1000:
import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000

在另一个方向,使用time.strptime(),传入由time.gmtime()创建的struct_time元组,首先将时间戳除以1000:

演示:

timestamp = 13668315
import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000
import time datestr = "Wed Apr 24 19:25:06 2013 GMT" time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000time.strftime("%a %d %b %Y %H:%M:%S GMT",time.gmtime(timestamp / 1000.0))
>>> datestr = "Wed Apr 24 19:25:06 2013 GMT" >>> time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000 13668279
import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000

.0
>>> timestamp = 13668315

import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr,"%a %b %d %H:%M:%S %Y %Z")) * 1000>>> time.strftime("%a %d %b %Y %H:%M:%S GMT",time.gmtime(timestamp / 1000.0)) 'Wed 24 Apr 2013 19:25:06 GMT'

猜你在找的Python相关文章