Setting Time and Date Format in Python

I have a dataset with a time column and a separate date column in .xlsx format.

time column has values in the below format:

  • 12:32:21.499145197
  • 12:32:21.499145197

date column has values in the below format:

  • Apr 10, 2018

  • Apr 10, 2018

When I read the Excel file in Python, both get object datatype. So I first correct the datatypes.

For date I use below code:

df[dateConv]= pd.to_datetime(df[date])
df[dateConv]

I am unable to correct the datatype for the time column. I tried the below option, but it gives me a day field as well, in addition to fixing the time's datatype.

df[timeConv]= pd.to_timedelta(df[Time])
df[timeConv]

Gives:

0       0 days 12:32:21.499136953
1       0 days 12:32:21.499145197

Also tried to use to_datetime and format option so it skips date. See below:

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

Get ValueError: unconverted data remains: .499136953

I also try a 2 step approach: Step 1: convert to datetime64. Step 2: trim date.

df[timeConv]= pd.to_datetime(df[Time])
df[timeConv]

2021-12-29 12:59:13.575038
Name: timeConv, Length: 50, dtype: datetime64[ns]

df[timeConv]= df['timeConv'].dt.time
df[timeConv]

I get time, but the datatype is back to object.

12:59:13.575038
Name: timeConv, Length: 50, dtype: object

Please help. Also, I did not merge both time and date columns as I don't know if it's the best way as of now but may merge later if useful :).

Thanks.

Topic time excel dataset python

Category Data Science

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.