from string to datatime in python

48 Views Asked by At

I have a dataset including all days in 2020 where solar and wind generation is measured on a 15 basis:

01.01.2020 00:00 - 01.01.2020 00:15

How do I convert this to datatime?

header and first row

I already tried this:

dftotalload2020['Time (CET/CEST)'] = pd.to_datetime(dftotalload2020['Time (CET/CEST)'], format='%d.%m.%Y %H:%M - %d.%m.%Y %H:%M')

but I get an error: error

1

There are 1 best solutions below

6
mozway On

You can't provide several times the same fields to to_datetime, rather extract only one of the two date and convert to datetime:

df['date'] = pd.to_datetime(df['MTU (CET/CEST)'].str.extract('(.*) -',
                                                             expand=False))

Output:

                        MTU (CET/CEST)       date
0  01.01.2020 00:00 - 01.01.2020 00:15 2020-01-01

Or split and convert both:

df[['date1', 'date2']] = (df['MTU (CET/CEST)'].str.split(r'\s*-\s*', expand=True)
                          .apply(pd.to_datetime)
                         )

Output:

                        MTU (CET/CEST)      date1               date2
0  01.01.2020 00:00 - 01.01.2020 00:15 2020-01-01 2020-01-01 00:15:00