将时间戳从数据框列转换为日期格式

时间:2020-06-22 02:43:49

标签: python pandas datetime timestamp

以下数据帧是

的结果
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]

将时间戳转换为日期格式的方式是什么?

2 个答案:

答案 0 :(得分:0)

将该列括在list()中。

print(list(top5['A'].astype('datetime64[ns]')))

答案 1 :(得分:0)

要从日期时间列中获取字符串列表,请使用

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']