首页 > 解决方案 > 更改python数据框中的日期时间格式

问题描述

我有以下 csv 文件并且我在使用 python pandas 作为数据框时打开了。我需要将文件修改如下: 1 - 将列(本地时间)重命名为日期 2 - 从列(日期)中删除除日期本身之外的任何内容(例如 2.6.2019) 3- 将日期格式更改为 mm/dd/ yyyy 4 - 将新文件导出为 csv 谢谢 在此处输入图像描述

标签: python-3.xpandascsvdataframedatetime

解决方案


使用pd.to_datetime时要传递的关键参数是dayfirst=True。然后,使用.dt.strftime('%m/%d/%Y')更改为所需的格式。我还为您提供了一个如何重命名列和读取/写入 .csv 的示例。再一次,我知道你在移动,但下一次,我会表现出更多的努力。

import pandas as pd
# df=pd.read_csv('filename.csv')
# I have manually created a dataframe below, but the above is how you read in a file.
df=pd.DataFrame({'Local time' : ['11.02.2015 00:00:00.000 GMT+0200',
                                '12.02.2015 00:00:00.000 GMT+0200',
                                '15.03.2015 00:00:00.000 GMT+0200']})
#Converting string to datetime and changing to desired format
df['Local time'] = pd.to_datetime(df['Local time'], 
                                  dayfirst=True).dt.strftime('%m/%d/%Y')
#Example to rename columns
df.rename(columns={'Local time' : 'Date'}, inplace=True)
df.to_csv('filename.csv', index=False)
df

推荐阅读