D.Banerjee
D.Banerjee

Reputation: 91

Getting error while trying to parse dates in python

I have a dataset like this

df_NO2

  rec                             pm1 pm2p5   pm10
0 2019-05-31T13:42:27.514+00:00   1.8 43.8    3.5
1 2019-05-31T13:42:37.497+00:00   1.6 46.4    3.3
2 2019-05-31T13:42:47.497+00:00   1.8 88.4    4.5
3 2019-05-31T13:42:57.498+00:00   2.8 34.9    5.4
4 2019-05-31T13:43:07.499+00:00   2.9 93.8    6.9

I wanted to change the date and time format of "rec" column to

df_NO2

         rec                    pm1 pm2p5   pm10
0   2019-05-31 13:42:27         1.8  43.8   3.5
1   2019-05-31 13:42:37         1.6  46.4   3.3
2   2019-05-31 13:42:47         1.8  88.4   4.5
3   2019-05-31 13:42:57         2.8  34.9   5.4
4   2019-05-31 13:43:07         2.9  93.8   6.9

I have tried using the code

import dateutil.parser

d = dateutil.parser.parse(df_NO2['rec'])
print(d.strftime('%yyyy-%mm-%dd %hh:%mm'))

But I am getting an error message

Parser must be a string or character stream, not Series.

Can someone please help?

Upvotes: 1

Views: 194

Answers (1)

Stef
Stef

Reputation: 30669

pd.to_datetime(df_NO2.rec).dt.strftime(%Y-%m-%d %H:%M)

Output:

0    2019-05-31 13:42
1    2019-05-31 13:42
2    2019-05-31 13:42
3    2019-05-31 13:42
4    2019-05-31 13:43

df_NO2['rec'] returns a whole column (series) which can't be processed by strftime. Instead, you need to apply strftime to each element of the series.

Besides, you got the format specifiers wrong, see e.g. here for reference.

Upvotes: 1

Related Questions