Prateek
Prateek

Reputation: 5

Pandas - New column is a difference between 2 timestamps. How to convert this into hours?

Original data

Touch Time        Install Time
3/28/2019 14:06  3/28/2019 15:34
3/27/2019 19:23  3/28/2019 15:22
3/28/2019 15:01  3/28/2019 15:18
3/28/2019 12:41  3/28/2019 15:18
3/27/2019 12:10  3/28/2019 15:08

After this, I read the csv using read_csv and created a new column diff that's

df['diff'] =  pd.to_datetime(df['Install Time']) - pd.to_datetime(df['Touch Time'])

This creates a column diff:

      Touch Time     Install Time          diff
0   3/28/2019 14:06  3/28/2019 15:34    0 days 01:28:00
1   3/27/2019 19:23  3/28/2019 15:22    0 days 19:59:00
2   3/28/2019 15:01  3/28/2019 15:18    0 days 00:17:00
3   3/28/2019 12:41  3/28/2019 15:18    0 days 02:37:00
4   3/27/2019 12:10  3/28/2019 15:08    1 days 02:58:00

For my analysis, I want to convert the values in diff column into hours and then plot it using matplotlib.

I want the final data to look like:

0 days 01:28:00 should reflect as 1 

1 days 02:58:00 should reflect as 26

Upvotes: 0

Views: 34

Answers (2)

philshem
philshem

Reputation: 25351

Another way to do it would be:

df['diff_hours']=df['diff']/np.timedelta64(1,'h')

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153510

Use total_seconds then divide by 3600 to convert to hours.

df['diff_hours'] = df['diff'].dt.total_seconds() / 3600

Upvotes: 3

Related Questions