Marc_Law
Marc_Law

Reputation: 25

Python converting time from string to timedelta to find time difference

how do I convert string to timedelta in order to create a new column within my dataframe?

from  pandas as pd
from numpy as np
from datetime import timedelta

pricetime = pd.DataFrame({'price1':[22.34, 44.68, 52.98], 'time1':['9:48:14', '15:54:33', '13:13:22'],'price2':[28.88, 47.68, 22.32], 'time2':['10:52:44', '15:59:59', '10:12:22']})

pricetime['price_change'] = np.where(pricetime['time1'] < pricetime['time2'], (pricetime['price1'] - pricetime['price2'])/pricetime['price2'], np.nan)
pricetime['time_diff'] = np.where(pricetime['time1'] < pricetime['time2'], pricetime['time2'] - pricetime['time1'], np.nan)

When I do this. I get an error for the time where I'm subtracting the two different times.

I tried to do this but it gave me an error:

pricetime['price_change'] = np.where((datetime.strptime(pricetime['time1'], '%H:%M:%S') < datetime.strptime(pricetime['time2'], '%H:%M:%S')), (pricetime['price1'] - pricetime['price2'])/pricetime['price2'], np.nan)
pricetime['time_diff'] = np.where((datetime.strptime(pricetime['time1'], '%H:%M:%S') < datetime.strptime(pricetime['time2'], '%H:%M:%S'), datetime.strptime(pricetime['time2'], '%H:%M:%S') - datetime.strptime(pricetime['time1'], '%H:%M:%S'), np.nan)

The error it gave is:

TypeError: strptime() argument 1 must be str, not Series

Upvotes: 0

Views: 96

Answers (2)

Aking
Aking

Reputation: 683

after a discussion with @Marc_Law the answer he looked for is:

pricetime['time_diff'] = pd.to_datetime(pricetime['time2']) - pd.to_datetime(pricetime['time1'])
pricetime.loc[pd.to_datetime(pricetime['time1']) >= pd.to_datetime(pricetime['time2']),'time_diff'] = np.nan
pricetime['time_diff'] = pricetime['time_diff'].apply(lambda x: str(x).split(' ')[-1:][0])

what he needed is to have the difference only if the value in time1 column was smaller than the value in time2 column, otherwise put np.nan. than return it to string without the "X days".

Upvotes: 2

Charchit Agarwal
Charchit Agarwal

Reputation: 3827

If you only want to find the difference in time, then you can follow this sample

from datetime import datetime


foo = '9:48:14'
bar = '15:54:33'

foo = datetime.strptime(foo, '%H:%M:%S')
bar = datetime.strptime(bar, '%H:%M:%S')

print(bar - foo)

Output

6:06:19

Further reading

Upvotes: 0

Related Questions