-1

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?

  • 2
    please post a reproducible example https://stackoverflow.com/help/minimal-reproducible-example I tried with just two rows with time as you indicated and it got imported without date – Naveed Oct 07 '22 at 20:16
  • I don't understand what data you have. Better show table or even better create code with we could copy and test. – furas Oct 07 '22 at 22:18
  • Below is imported from CSV: | DATE | HOUR | ------------------------ | 2022/03/29 | 14:00 | | 2021/06/25 | 21:45 | ------------------------ DATE is imported as datetime. If HOUR is imported as datetime it is converted to datetime with today's date "2022:10:10 14:00" import datetime as dt import pandas as pd parse_dates=['DATE'] df = pd.read_csv(filepath, parse_dates=parse_dates, infer_datetime_format=True) Maybe datetime is not the correct type, but I could not find a different time to host the time only. – user1015767 Oct 10 '22 at 20:10

1 Answers1

0

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
Jed
  • 1,823
  • 4
  • 20
  • 52
  • Thank you, its close, the only thing is that the time column type, is an object, and not a datetime: ` >>> df.dtypes x1 int64 time_string object time object dtype: object ` – user1015767 Oct 10 '22 at 18:36
  • I updated the code to show that the data type is actually a `datetime.time`. Pandas obscures the data types sometimes, but if you look at the individual values (using `apply` here), you can see they're the right data type. – Jed Oct 10 '22 at 19:37