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
Solution 1:
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:
month02019-01-0112019-02-0122019-03-0132019-04-0142019-05-0152019-06-0162019-07-0172019-08-0182019-09-0192019-10-01102019-11-01112019-12-01
Solution 2:
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
Post a Comment for "Pandas To Datetime With German Date Format?"