将 epoch 时间从 JSON 转换为标准日期时间的 Python 代码?

huangapple go评论64阅读模式
英文:

Convert epoch time to standard datetime from json python?

问题

我有一个JSON:

[{'id':'1',
'name':'rob',
'created':'1577431544986' },

{'id':'2',
'name':'tom',
'created':'1566431234567' }]

我需要将JSON中的UNIX时间戳转换为标准的日期时间。

我的最终输出应该是:

[{'id':'1',
'name':'rob',
'created':'27-12-2019' },

{'id':'2',
'name':'tom',
'created':'22-08-2019' }]

我已经完成的部分:

我可以为单个变量找出如何做到这一点:

import datetime
time = '1566431234567'
your_dt = datetime.datetime.fromtimestamp(int(time)/1000)
print(your_dt.strftime("%d-%m-%Y"))

'22-08-2019'

但如何在上面的JSON中使用相同的方法呢?

英文:

I have a JSON:

[{'id':'1',
'name':'rob',
'created':'1577431544986' 
    },

{'id':'2',
'name':'tom',
'created':'1566431234567' 
    }]

I need to convert the UNIX timestamp present in the JSON to standard DateTime.

My final output should be:

[{'id':'1',
'name':'rob',
'created':'27-12-2019' 
    },

{'id':'2',
'name':'tom',
'created':'22-08-2019' 
    }]

What i have done:

I'm able to figure out doing it for single variable:

import datetime
time = '1566431234567'
your_dt = datetime.datetime.fromtimestamp(int(time)/1000)
print(your_dt.strftime("%d-%m-%Y"))


'22-08-2019'

But how to use the same in above JSON?

答案1

得分: 2

Epoch time(时代时间)是自1970年1月1日00:00:00以来经过的秒数,您可以将其转换为人类日期时间,如下所示:

import time
# 自纪元以来经过的秒数
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("本地时间:", local_time)

更多详细信息,请查阅 https://docs.python.org/3/library/time.html

英文:

Epoch time is the number of seconds passed since January 1, 1970, 00:00:00 and you can convert it to human date time as

import time
# seconds passed since epoch
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("Local time:", local_time)	

For more details check https://docs.python.org/3/library/time.html

huangapple
  • 本文由 发表于 2020年1月6日 21:05:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定