datetime - Splitting time by the hour Python -


i have dataframe df1 this, starttime , endtime datetime objects.

starttime endtime

9:08 9:10
9:10 9:35
9:35 9:55
9:55 10:10
10:10 10:20

if endtime.hour not same startime.hour, split times this

starttime endtime

9:08 9:10

9:10 9:55

9:55 10:00

10:00 10:10

10:10 10:20

essentially insert row existing dataframe df1. have looked @ ton of examples haven't figured out how this. if question isn't clear please let me know.

thanks

this want ...

# load data dataframe data="""starttime endtime 9:08 9:10 9:10 9:35 9:35 9:55 9:55 10:10 10:10 10:20 """ stringio import stringio # import io python 3 df = pd.read_csv(stringio(data), header=0, sep=' ', index_col=none)  # convert strings pandas timestamps (we ignore date bit) ... import datetime dt df.starttime = [dt.datetime.strptime(x, '%h:%m') x in df.starttime] df.endtime = [dt.datetime.strptime(x, '%h:%m') x in df.endtime]  # assumption - intervals less 60 minutes #            - ie. no multi-hour intervals  # add rows dfa = df[df.starttime.dt.hour != df.endtime.dt.hour].copy() dfa.endtime = [dt.datetime.strptime(str(x), '%h') x in dfa.endtime.dt.hour]  # play start hour ... df.starttime = df.starttime.where(df.starttime.dt.hour == df.endtime.dt.hour,     other = [dt.datetime.strptime(str(x), '%h') x in df.endtime.dt.hour])  # bring , sort df = pd.concat([df, dfa], axis=0) #top/bottom df = df.sort('starttime')  # convert timestamps times easy reading df.starttime = [x.time() x in df.starttime] df.endtime = [x.time() x in df.endtime] 

and yields

in [40]: df out[40]:    starttime   endtime 0  09:08:00  09:10:00 1  09:10:00  09:35:00 2  09:35:00  09:55:00 3  09:55:00  10:00:00 3  10:00:00  10:10:00 4  10:10:00  10:20:00 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -