0

A dataframe column with values in 'time' format needs to be added with 24 hours. eg: if 24 hours is getting added with value 10:30:30 then result expected is 34:30:30,the below code piece(added as image) generates '0 days 10:30:30'

enter image description here can anyone please guide me not get 0days and to get the 24 hours to add with hour value.

Sukanya
  • 33
  • 1
  • 1
  • 9
  • 1
    Please add your code into your question, not a screenshot of it – Wondercricket Mar 08 '19 at 14:16
  • Possible duplicate of [How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?](https://stackoverflow.com/questions/28954093/how-to-add-subtract-time-hours-minutes-etc-from-a-pandas-dataframe-index-wh) – Chris Adams Mar 08 '19 at 14:51

1 Answers1

1

Sample:

N = 10
np.random.seed(2019)
rng = pd.date_range('2017-04-03 15:30:20', periods=N, freq='13.3T')
df = pd.DataFrame({'vstime': np.abs(np.random.choice(rng, size=N) - 
                                 np.random.choice(rng, size=N))})

print (df)
    vstime
0 00:39:54
1 00:13:18
2 01:06:30
3 01:19:48
4 00:13:18
5 00:13:18
6 01:46:24
7 01:06:30
8 00:39:54
9 01:46:24

Instead your code use to_timedelta and add Timedelta.

df['vstime'] = pd.to_timedelta(df['vstime']) + pd.Timedelta(24, unit='h') 

Formating timedelta is not native suported, so need custom function:

def f(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return ('{}:{:02d}:{:02d}').format(int(hours), int(minutes), int(seconds)) 

df['duration'] = df['vstime'].apply(f)
print (df)
           vstime  duration
0 1 days 00:39:54  24:39:54
1 1 days 00:13:18  24:13:18
2 1 days 01:06:30  25:06:30
3 1 days 01:19:48  25:19:48
4 1 days 00:13:18  24:13:18
5 1 days 00:13:18  24:13:18
6 1 days 01:46:24  25:46:24
7 1 days 01:06:30  25:06:30
8 1 days 00:39:54  24:39:54
9 1 days 01:46:24  25:46:24
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252