Lee
Lee

Reputation: 21

Formating df.to_datetime results in NaT entries

My final goal is to make a plot for a specific time range (just showing hour and minute). This is how my original df looks like:

Herzrate (bpm)  Zeit
0   NaN     2019-9-15 7:55
1   NaN     2019-9-15 7:55
2   NaN     2019-9-15 7:55
...
8   85.0    2019-9-15 7:55
9   85.0    2019-9-15 7:55
10  85.0    2019-9-15 7:55
...
49925   106.0   2019-9-15 21:47

First I delete the NaT lines and after that I want to convert the objects to datetime to set a range, later on.

df.dropna(axis=0, how='any',inplace=True)
pd.to_datetime(df['Zeit'],format = '%H:%M', errors='coerce')

Unfortunatley as a result all entries are converted to NaT

...
49921   NaT
49922   NaT
49923   NaT
49924   NaT
49925   NaT
Name: Zeit, Length: 49515, dtype: datetime64[ns]

I do not really understand my mistake.

Converting instead without format= seems to work first, but when I trying to just print the hours and numbers with print(df['Zeit'].dt.strftime('%H:%M')) it results in the following error: "Can only use .dt accessor with datetimelike values"

EDIT: Erfans solution worked totally fine. Thanks for that!

Upvotes: 0

Views: 206

Answers (1)

Erfan
Erfan

Reputation: 42916

Your format is wrong, you have to access the hour and minute attribute after converting it to datetime:

pd.to_datetime(df['Zeit'],errors='coerce').dt.strftime('%H:%M')

Upvotes: 1

Related Questions