用12位数字转换Json Date Python日期时间 [英] Convert Json Date with 12 digits Python Datetime
问题描述
我收到一个 json
,我将其转换为 DataFrame df
.该列之一带有日期"这种格式/Date(950842800000)/
,/Date(1000436400000)/
,...
I am receiving a json
which I convert to DataFrame df
. One of the column is with Dates this format
/Date(950842800000)/
, /Date(1000436400000)/
, ...
问题在于,其中一个日期有12位数字,其他日期有13位数字.有13位数字的这个数字可以很好地转换,而有12位数字的则有问题.我的转换方式
The problem is that One of this dates has 12 digit and the others 13 digits. This one with 13 digits are converted fine, and with 12 there is a problem. The way I am converting
df["Data"] = df["Date"].apply(lambda x: datetime.fromtimestamp(int(x[6:-2][:10])) if len(x) > 12 else datetime.fromtimestamp(int(x[6:-2][:11])))
不能使用12位数字.谢谢您的帮助.
doesn´t work for 12 digits. Thank You for help.
推荐答案
简短:
lambda x: datetime.fromtimestamp(int(x[6:-2][:-3]))
长
如果您有这样的输入数据:
If you have such input data:
"/Date(950842800000)/",
"/Date(1000436400000)/"
只需进行少量修改即可使脚本正常工作:
Than a few modifications will make script working correctly:
from datetime import datetime
dates = [
"/Date(950842800000)/",
"/Date(1000436400000)/"
]
for d in dates:
l = lambda x: datetime.fromtimestamp(int(x[6:-2][:9])) if len(x) < 21 else datetime.fromtimestamp(
int(x[6:-2][:10]))
print(l(d))
产生:
2000-02-18 04:00:00
2001-09-14 05:00:00
您期望什么.
但是我们可能为了简单起见,可以只使用:
But then we may think to simplicity, you may just use:
from datetime import datetime
dates = [
"/Date(950842800000)/",
"/Date(1000436400000)/"
]
for d in dates:
l = lambda x: datetime.fromtimestamp(int(x[6:-2][:-3]))
print(l(d))
这篇关于用12位数字转换Json Date Python日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!