python - 如何在 python 中将宇宙数据的时间戳转换为日期时间格式?

标签 python pandas azure azure-cosmosdb azure-cosmosdb-sqlapi

查询 cosmos db 后,我在数据帧(df)中收到一个 ts 列,其中的日期时间格式如下

df
_ts         etag
1646255207   xyz
1646257427   abc
1646297798
1646333451   dfg

如何将其转换为日期时间格式。我想要的原因是,我只想要过去 24 小时的数据。

我试过了-

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'

是否有更好的方法来向 _ts 添加过滤器并从 _ts 本身获取最近 24 小时的数据?

最佳答案

pd.to_datetimeunit="s"一起使用:

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

打印:

          _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
<小时/>

获取最近 24 小时数据:

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

关于python - 如何在 python 中将宇宙数据的时间戳转换为日期时间格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71942731/

相关文章:

python - Urllib2 & BeautifulSoup : Nice couple but too slow - urllib3 & threads?

python - 将 Python 方法转换为 C 扩展的好处?

python - pandas groupby 适用于系列,但不适用于选择整个数据框

azure - 如何在性能缓慢的应用程序上选择 Azure 应用程序服务计划?

azure - Nextjs 应用程序从 Azure 应用程序服务读取配置

python - 如何在Python中使用正则表达式获取两个特定字符之间的第一个整数?

python - Pandas 出现故障?无法覆盖值

python - 从列列表中的括号内提取数字

azure - 为什么 Azure Functions 创建 V1 存储帐户?

python - PIL替换颜色的最佳方法?