Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas to datetime with German date format?

I have a dataframe with dates in the following manner:

'Jan 2019', 'Feb 2019', 'Mär 2019', 'Apr 2019', 'Mai 2019', 'Jun 2019', 'Jul 2019', 'Aug 2019', 'Sep 2019', 'Okt 2019', 'Nov 2019', 'Dez 2019'

I am trying to convert the column to datetime using

pd.to_datetime(df.month, format='%b%Y', errors='ignore')

Unfortunately, to_datetime retuns objects instead of datetimes. I believe it's because of the German spelling of the date (e.g. 'Mär 2019' instead of 'Mar 2019' or 'Dez 2019' instead of 'Dec 2019').

What would be a good general solution to this problem?

like image 490
Rachel Avatar asked Dec 23 '22 20:12

Rachel


2 Answers

If you have german "locale" installed (it is OS dependendent and topic for separate question), here is an easy and clean way:

import pandas as pd
import locale

a = ['Jan 2019', 'Feb 2019', 'Mär 2019', 'Apr 2019', 'Mai 2019', 
     'Jun 2019', 'Jul 2019', 'Aug 2019', 'Sep 2019', 'Okt 2019', 'Nov 2019', 'Dez 2019']

df = pd.DataFrame({'month':a})

locale.setlocale(locale.LC_ALL, 'de_DE')
df['month'] = pd.to_datetime(df['month'], format='%b %Y')

Output:

        month
0  2019-01-01
1  2019-02-01
2  2019-03-01
3  2019-04-01
4  2019-05-01
5  2019-06-01
6  2019-07-01
7  2019-08-01
8  2019-09-01
9  2019-10-01
10 2019-11-01
11 2019-12-01
like image 81
Quant Christo Avatar answered Mar 07 '23 08:03

Quant Christo


I think one possible solution is use Series.replace before converting to datetimes:

a = ['Jan 2019', 'Feb 2019', 'Mär 2019', 'Apr 2019', 'Mai 2019', 
     'Jun 2019', 'Jul 2019', 'Aug 2019', 'Sep 2019', 'Okt 2019', 'Nov 2019', 'Dez 2019']

df = pd.DataFrame({'month':a})

d = {'Mär':'Mar', 'Mai':'May','Okt':'Oct','Dez':'Dec'}
df['month']=pd.to_datetime(df['month'].replace(d, regex=True), format='%b %Y', errors='coerce')
print (df)
        month
0  2019-01-01
1  2019-02-01
2  2019-03-01
3  2019-04-01
4  2019-05-01
5  2019-06-01
6  2019-07-01
7  2019-08-01
8  2019-09-01
9  2019-10-01
10 2019-11-01
11 2019-12-01
like image 34
jezrael Avatar answered Mar 07 '23 07:03

jezrael