Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...