Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

python 3.x - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...