Pandas - Add seconds from a column to datetime in

2020-08-13 05:12发布

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 ).

标签: python pandas
2条回答
老娘就宠你
2楼-- · 2020-08-13 05:37

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')
查看更多
三岁会撩人
3楼-- · 2020-08-13 05:46
df.StartDate = df.apply(lambda x: pd.to_datetime(x.StartDate)+pd.Timedelta(Second(df.duration)) ,axis = 1)
查看更多
登录 后发表回答