在Python数据框中更改日期时间格式

时间:2020-03-08 00:14:37

标签: python-3.x pandas csv dataframe datetime

我有以下csv文件 而且我已经开始使用python pandas作为数据框。 我需要修改文件,如下所示: 1-将列(本地时间)重命名为Date 2-从日期列中删除除日期本身以外的任何内容(例如2.6.2019) 3-将日期格式更改为mm / dd / yyyy 4-将新文件导出为csv 谢谢 enter image description here

1 个答案:

答案 0 :(得分:1)

使用 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