Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Add seconds from a column to datetime in other column

Tags:

python

pandas

I have a dataFrame with two columns, ["StartDate" ,"duration"] the elements in the StartDate column are datetime type, and the duration are ints.

Something like:

StartDate  Duration
08:16:05    20  
07:16:01    20

I expect to get:

EndDate 
08:16:25
07:16:21

Simply add the seconds to the hour.

I'd being checking some ideas about it like the delta time types and that all those datetimes have the possibilities to add delta times, but so far I can find how to do it with the DataFrames (in a vector fashion, cause It might be possible to iterate over all the rows performing the operation ).

like image 486
RolandDeschain Avatar asked Sep 06 '17 17:09

RolandDeschain


People also ask

How do I calculate time difference between two columns in pandas?

To calculate time difference between two Python Pandas columns in hours and minutes, we can subtract the datetime objects directly. We create a Panda DataFrame with 3 columns. Then we set the values of the to and fr columns to Pandas timestamps.

What does sub () do in pandas?

Pandas DataFrame sub() Method The sub() method subtracts each value in the DataFrame with a specified value. The specified value must be an object that can be subtracted from the values in the DataFrame.

What does Parse_dates do in pandas?

We can use the parse_dates parameter to convince pandas to turn things into real datetime types. parse_dates takes a list of columns (since you could want to parse multiple columns into datetimes ).

What is DatetimeIndex pandas?

class pandas. DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.


2 Answers

consider this df

    StartDate   duration
0   01/01/2017  135
1   01/02/2017  235

You can get the datetime column like this

df['EndDate'] = pd.to_datetime(df['StartDate']) + pd.to_timedelta(df['duration'], unit='s')
df.drop('StartDate,'duration', axis = 1, inplace = True)

You get

    EndDate             
0   2017-01-01 00:02:15 
1   2017-01-02 00:03:55 

EDIT: with the sample dataframe that you posted

df['EndDate'] = pd.to_timedelta(df['StartDate']) + pd.to_timedelta(df['Duration'], unit='s')
like image 173
Vaishali Avatar answered Sep 24 '22 18:09

Vaishali


df.StartDate = df.apply(lambda x: pd.to_datetime(x.StartDate)+pd.Timedelta(Second(df.duration)) ,axis = 1)
like image 28
A.Kot Avatar answered Sep 22 '22 18:09

A.Kot