简体   繁体   中英

How to make end time of 1st row as start time of 2nd row in python

How can I make end time of 1st row as start time of 2nd row (I intend to add some value in seconds to the start time in every row and the end time of the very same row needs to be start time of next row).

For example,

start-time|time_to_add|endtime

10:00:00  |30 secs   |10:00:30

10:00:30  | 15 secs  | 10:00:45

10:00:45  | 10 secs  | 10:00:55

Any help would be appreciated.

Thanks

edit

starttime  | val_to_add |  endtime

10:30:00   | 30     |   10:30:00 + 0:0:30

10:30:00 + 0:0:30  | 30   | 10:30:00 + 0:0:30 + 0:0:30

Use:

df['start-time'] = pd.to_timedelta(df['start-time'])
df['time_to_add']=pd.to_timedelta(df['time_to_add'].replace(' sec', '', regex=True), unit='s')
df['end-time'] = df['start-time'] + df['time_to_add'] 

Here is a small example of how to do it if time_to_add is a list of values.

import pandas as pd
import numpy as np

df = pd.DataFrame()
initial_start_time = pd.to_timedelta('10:00:00')
time_to_add = ['0:00:30', '0:00:15', '0:00:15', '0:00:30', '0:00:20']
time_to_add = [pd.to_timedelta(x) for x in time_to_add]

df['time_to_add'] = time_to_add
df['end_time'] = [initial_start_time + x for x in np.cumsum(time_to_add)]
df['start_time'] = [initial_start_time] + list(df['end_time'][:-1])

df = df[['start_time', 'time_to_add', 'end_time']]

The column time_to_add is just your intervals. The column end_time adds the intervals times to the initial start time and the columnn start_time takes the end times and shifts them by one row. The last line is just for reordering the columns.

Hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM