python - 将时间戳从数据框列转换为日期格式
问题描述
以下数据框是
top5 = df.nlargest(5,columns='B',keep='all')
A B C D E F G H I
77 2013-08-17 42302 2278503 100644.38 5021507.24 72471 5729 5729 217
70 2013-08-10 42245 2016000 103374.87 4492859.82 69996 5567 5567 223
74 2013-08-14 42226 2154625 78504.31 4766845.59 71481 1727 1727 219
66 2013-08-06 42086 1871575 81608.23 4209532.51 68744 1778 1778 222
59 2013-07-30 42032 1611459 79312.12 3691785.45 65855 1701 1701 237
我想只打印日期作为结果。我已经尝试过这样的事情来只打印A
列:
print(top5['A'].values.tolist())
但它给了我这个结果:
[1376697600000000000, 1376092800000000000, 1376438400000000000, 1375747200000000000, 1375142400000000000]
但我需要这样的结果:
[2013-08-17,2013-08-10,2013-08-14,2013-08-06,2013-07-30]
将此时间戳转换为日期格式的方法是什么?
解决方案
要从日期时间列中获取字符串列表,请使用
import pandas as pd
# what you have is like
top5 = pd.DataFrame({'A': pd.to_datetime(['2013-08-17', '2013-08-10', '2013-08-14'])})
# note the column A is of dtype datetime
# format to string using strftime and then cast to_list():
l_A = top5['A'].dt.strftime('%Y-%m-%d').to_list()
# l_A
# ['2013-08-17', '2013-08-10', '2013-08-14']
推荐阅读
- asp.net-core - Asp.net 核心 Kestrel 服务器和 CLI
- java - 信任 SSL 证书:Commons HTTP 客户端如何比标准 Java 更信任?
- lua - 每个 taglist 项目的不同背景颜色 AwesomeWM
- r - 为什么我绘制随时间增长的函数不起作用?
- c# - 压缩文件时出现异常
- javascript - 将类添加到模板克隆中的元素(Google 脚本)
- json - Shopify 中返回了错误的 JSON 数据
- azure - Azure 翻译 API - 缓存
- regex - 用编号分割bash中的长行
- anylogic - 是否可以以编程方式将代理作为资源添加到资源池中?