English 中文(简体)
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
最佳回答

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
问题回答

Using to_timedelta,we can convert string to time format(timedelta64[ns]) by specifying units as second,min etc.,

dfc[ Time_of_Sail ] = pd.to_timedelta(dfc[ Time_of_Sail ], unit= s )

This seems to work:

dfc[ Time_of_Sail ] = pd.to_datetime(dfc[ Time_of_Sail ], format= %H:%M:%S ).apply(pd.Timestamp)

If anyone is searching for a more generalized answer try

dfc[ Time_of_Sail ]= pd.to_datetime(dfc[ Time_of_Sail ])

If you just want a simple conversion you can do the below:

import datetime as dt

dfc.Time_of_Sail = dfc.Time_of_Sail.astype(dt.datetime)

or you could add a holder string to your time column as below, and then convert afterwards using an apply function:

dfc.Time_of_Sail = dfc.Time_of_Sail.apply(lambda x:  2016-01-01   + str(x))
dfc.Time_of_Sail = pd.to_datetime(dfc.Time_of_Sail).apply(lambda x: dt.datetime.time(x))

(Python 3)
You can apply pd.to_datetime() and datetime.time to the Series with apply() function and dt accessor: dfc[ Time_of_Sail ].apply(pd.to_datetime).dt.time.

Recap

import pandas as pd

# Original DataFrame
>>> dfc = pd.DataFrame(
>>>     {
>>>          Temp_Reading : [1, 2, 3, 4, 5],
>>>          Time_of_Sail : [ 11:33:11 ,  16:29:05 ,  09:37:56 ,  21:43:31 ,  17:42:06 ]
>>>     }
>>>> )

# Convert to datetime.time object
>>> dfc[ Time_of_Sail ] = dfc[ Time_of_Sail ].apply(pd.to_datetime).dt.time
>>> dfc[ Time_of_Sail ]
    0    11:33:11
    1    16:29:05
    2    09:37:56
    3    21:43:31
    4    17:42:06
    Name: Time_of_Sail, dtype: object

Data type
Indeed dfc.dtypes returns Time_of_Sail object, but you ll see they are datetime.time objects at a closer look:

>>> dfc[ Time_of_Sail ][0]
datetime.time(11, 33, 11)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签