How to import a CSV with an hour/minute string as a timestamp to panda dataset

401 Views Asked by At

I need to import a CSV to a panda dataset. The CSV has columns with just a time of the day, an example is a columns with "16:45" at a minutes level, another column has "21:03:39" at the seconds level. Importing it using read_cvs and using parse_dates for the columns will not keep it as is, it will convert it to "2022/10/07 16:45" or "2022/10/07 21:03:39" for the second example. How can I import it and have the type as Time without adding the date?

1

There are 1 best solutions below

2
Jed On

What about something like this?

import datetime as dt
import pandas as pd

df = pd.DataFrame([[1, '16:45'],
                   [2, '21:03:39']], columns=['x1', 'time_string'])
df['time'] = pd.to_datetime(df['time_string']).apply(lambda t: dt.time(t.hour, t.minute, t.second))

# Output these to show it works
df.head()
df['time'].apply(lambda x: type(x))

Returns this:

   x1 time_string      time
0   1       16:45  16:45:00
1   2    21:03:39  21:03:39

0    <class 'datetime.time'>
1    <class 'datetime.time'>
Name: time, dtype: object