简体   繁体   English

如何将 python 中的时间戳转换为日期时间格式以获得 cosmos 数据?

[英]How do I convert timestamp to datetime format in python for cosmos data?

After querying cosmos db I receive a ts column in my dataframe(df) which has datetime in the below format查询 cosmos db 后,我的数据框 (df) 中收到一个 ts 列,其中的日期时间格式如下

df
_ts         etag
1646255207   xyz
1646257427   abc
1646297798
1646333451   dfg

How do I convert this to a datetime format.如何将其转换为日期时间格式。 The reason i want to is because, I only want data from last 24 hours.我想要的原因是,我只想要过去 24 小时的数据。

I tried-我试过了-

from datetime import datetime
d = "1646255207"
d = int(d[:10])
datetime.fromtimestamp(d).strftime('%Y-%m-%d %I:%M:%S %p')
Out[39]: '2022-03-02 04:06:47 PM'

Is there a better way to just add a filter to _ts and get last 24 hour data from _ts itself?有没有更好的方法来向 _ts 添加过滤器并从 _ts 本身获取最近 24 小时的数据?

Use pd.to_datetime with unit="s" :pd.to_datetimeunit="s"一起使用:

df["Date"] = pd.to_datetime(df["_ts"], unit="s")
print(df)

Prints:印刷:

          _ts  etag                Date
0  1646255207   xyz 2022-03-02 21:06:47
1  1646257427   abc 2022-03-02 21:43:47
2  1646297798  None 2022-03-03 08:56:38
3  1646333451   dfg 2022-03-03 18:50:51

And to get last 24h data:并获取最近 24 小时的数据:

print(df[df["Date"] > df["Date"].max() - pd.Timedelta(hours=24)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM