简体   繁体   English

pandas 选择 to_datetime 的原始格式

[英]pandas selecting original format of to_datetime

I have the following df:我有以下df:

df

index          Original Date                          
19.02.2021     19.02.2021  
19.02.2021     19.02.2021  
...                 
04.12.2020     04.12.2020 
03.12.2020     03.12.2020

I would like to set index column as an index, however it is at the moment string type object so, I convert it to datetime object and then set as an index.我想将索引列设置为索引,但是目前它是字符串类型 object 所以,我将其转换为日期时间 object 然后设置为索引。

df['index'] = pd.date_time(df['index'])
df = df.set_index('index')

It looks like this:它看起来像这样:

df

             Original Date
index          
2021-02-19   19.02.2021
2021-02-19   19.02.2021
2021-02-18   18.02.2021
2021-02-18   18.02.2021
2021-02-17   17.02.2021
...
2020-04-12   04.12.2020
2020-03-12   03.12.2020

As you can see pandas can succesfully convert some of the dates.如您所见,pandas 可以成功转换某些日期。 However some days like 04.12.2020 is converted to 12.04.2020 .然而,像04.12.2020这样的日子会转换为12.04.2020 So how can I specify the original format is 'dd.mm.yyyy' , so that pandas can convert this string object to datetime successfully.那么如何指定原始格式为'dd.mm.yyyy' ,以便 pandas 可以将此字符串 object 成功转换为日期时间。

You can add the format as a parameter您可以将格式添加为参数

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

Try the following:尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM