Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Pandas convert string to time only

I have the following Pandas dataframe in Python 2.7.

import pandas as pd trial_num = [1,2,3,4,5] sail_rem_time = ['11:33:11','16:29:05','09:37:56','21:43:31','17:42:06'] dfc = pd.DataFrame(zip(*[trial_num,sail_rem_time]),columns=['Temp_Reading','Time_of_Sail']) print dfc 

The dataframe looks like this:

  Temp_Reading Time_of_Sail              1     11:33:11              2     16:29:05              3     09:37:56              4     21:43:31              5     17:42:06 

This dataframe comes from a *.csv file. I use Pandas to read in the *.csv file as a Pandas dataframe. When I use print dfc.dtypes, it shows me that the column Time_of_Sail has a datatype object. I would like to convert this column to datetime datatype BUT I only want the time part - I don't want the year, month, date.

I can try this:

dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail']) dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']] 

but the problem is that the when I run print dfc.dtypes it still shows that the column Time_of_Sail is object.

Is there a way to convert this column into a datetime format that only has the time?

Additional Information:

To create the above dataframe and output, this also works:

import pandas as pd trial_num = [1,2,3,4,5] sail_rem_time = ['11:33:11','16:29:05','09:37:56','21:43:31','17:42:06'] data = [     [trial_num[0],sail_rem_time[0]],     [trial_num[1],sail_rem_time[1]],[trial_num[2],sail_rem_time[2]],     [trial_num[3],sail_rem_time[3]]     ] dfc = pd.DataFrame(data,columns=['Temp_Reading','Time_of_Sail']) dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail']) dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']] print dfc print dfc.dtypes 
like image 624
edesz Avatar asked Jun 14 '16 00:06

edesz


People also ask

How do you convert a string to just time in python?

Use strptime() function of a time module Use this step if you want to convert a string to a time object. Use the time. strptime(string[, format]) function. This function converts time in string format to a time object in time.

How do I convert a column to a time in Python?

Use pandas to_datetime() function to convert the column to DateTime on DataFrame. Use the format parameter of this method to specify the pattern of the DateTime string you wanted to convert.

How do you parse time in pandas?

The strftime to parse time, e.g. "%d/%m/%Y" . Note that "%f" will parse all the way up to nanoseconds.


1 Answers

These two lines:

dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail']) dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']] 

Can be written as:

dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'],format= '%H:%M:%S' ).dt.time 
like image 88
Merlin Avatar answered Sep 23 '22 12:09

Merlin