-2

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

Timus
  • 10,974
  • 5
  • 14
  • 28
J1999
  • 3
  • 2

1 Answers1

0

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
mozway
  • 194,879
  • 13
  • 39
  • 75
  • I dont understand what you mean. Do I have to use the data or the time and not both? If that's what you mean. How can I create a new column for the date and a new column for the time both converted to datetime? Thanks! – J1999 Mar 21 '23 at 10:12
  • What I mean is that `to_datetime` cannot understand two times the same format field (e.g. %Y), so you have to chose. Can you please provide a reproducible input of your example? – mozway Mar 21 '23 at 10:15
  • I provided an example of the outputs for clarity – mozway Mar 21 '23 at 10:17
  • You might also want to explore using a `Period` with `df['period'] = pd.PeriodIndex(pd.to_datetime(df['MTU (CET/CEST)'].str.extract('(.*) -', expand=False)), freq='15min')` – mozway Mar 21 '23 at 10:18
  • Thank you for the clear explanation! However, due to this split I am not sure how to plot the data. Can you also help me with that? I want the total load on the Y axis and the mean per day on the X axis.. – J1999 Mar 21 '23 at 12:12
  • I'm not sure which method you use to plot, but pass the correct columns as x and y. Please provide your current code if you need help. – mozway Mar 21 '23 at 12:48