如何在pandas中设置日期格式

2024-09-21 01:14:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python和pandas获取雅虎股票市场日期并保存到本地csv文件

DailyPrice = pd.read_csv(file, index_col=0)
print(DailyPrice.tail())

Date
2020-05-27           86.480003  84.370003  86.300003  86.180000  1917600.0 
2020-05-28           87.849998  86.059998  86.870003  86.690002  1908700.0

然后我更新日期

History = pdr.DataReader(ticker, start=Before_yesterday, end=Today, data_source='yahoo')
print(History.tail())

Date
2020-06-29  87.360001  86.110001  86.559998  87.290001  1302500.0  87.290001
2020-06-30  88.379997  87.235001  87.330002  88.269997   236377.0  88.269997

然后我加上日期

DailyPrice = DailyPrice.append(History)
print(DailyPrice.tail())

Date
2020-05-27           86.480003  84.370003  86.300003  86.180000  1917600.0 
2020-05-28           87.849998  86.059998  86.870003  86.690002  1908700.0
2020-06-29 00:00:00  87.360001  86.110001  86.559998  87.290001  1302500.0
2020-06-30 00:00:00  88.379997  87.235001  87.330002  88.269997   236377.0

所以,我的问题是: 如何像%Y-%m-%d一样格式化列日期,而不使用时间hh:mm:ss


Tags: 文件csvpandasreaddateindexcolhistory
3条回答

看起来您有一个DatetimeIndex,您可以尝试使用strftime

DailyPrice.index = DailyPrice.index.strftime('%Y-%m-%d')

我想我发现了问题所在

日期不是列的名称

DailyPrice.columns.values.tolist()
['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close']

那么,第一栏,日期,是什么

日期是索引

最后,问题得到了解决

DailyPrice.index = pd.to_datetime(DailyPrice.index, format = '%Y-%m-%d')

我想这是同一个问题one

df['Date'] = df['Date'].dt.date

应该行得通

相关问题 更多 >

    热门问题