Grymrch
Grymrch

Reputation: 45

Trying to convert Pandas Column with only [HH:DD], but getting [YYYY-DD-MM HH:MM:SS] back

I have a pandas column with the time format as [HH:DD], as shown below. I want to change the type to a time, with a bit of googling and looking around; to_timedate was what I should use.

0      NaN
1    06:56
2      NaN
3      NaN
4      NaN
Name: Time, dtype: object

I hacked together this piece of code to do it:

df['Time'] = pd.to_datetime(df['Time'], format= '%H:%M', errors='coerce')

But now I get this returned:

0                   NaT
1   1900-01-01 06:56:00
2                   NaT
3                   NaT
4                   NaT
Name: Time, dtype: datetime64[ns]

I don't need the date, only thing I need is the HH:DD. I tried playing around with a few of the parameters, hoping I could figure it out, but no avail. Can anyone point me in the right direction?

Upvotes: 3

Views: 110

Answers (1)

jezrael
jezrael

Reputation: 862701

If need processing later better is convert to timedeltas instead times by to_timedelta with add seconds:

df['Time'] = pd.to_timedelta(df['Time'].add(':00'), errors='coerce')
print (df)
      Time
0      NaT
1 06:56:00
2      NaT
3      NaT
4      NaT

But it is possible - add Series.dt.time for python objects times:

df['Time'] = pd.to_datetime(df['Time'], format= '%H:%M', errors='coerce').dt.time
print (df)
       Time
0       NaT
1  06:56:00
2       NaT
3       NaT
4       NaT

Upvotes: 2

Related Questions