简体   繁体   中英

how to calculate elapsed time in days and hours

Hi everyone I have two columns in datetime format and I want to make a new column with the elapsed time in days and a second column containing the rest in hours. please see the exemple:

my data :

# importing pandas as pd 
import pandas as pd 

# creating a dataframe 
df = pd.DataFrame({'DATE_IDENTIFIED': ['2019-06-27 10:42:50 ', '2019-06-28 13:11:58', '2019-06-20 13:12:23','2019-06-26 11:14:59','2019-06-26 11:16:04'], 
   'DATE_CLOSED': ['2019-09-27 10:40:38', '2019-06-28 19:11:22', 
   '2019-06-28 18:11:22','2019-06-26 13:13:38','2019-06-28 14:15:37']}) 


DATE_IDENTIFIED                   DATE_CLOSED
0   2019-06-27 10:42:50           2019-06-27 10:40:38
1   2019-06-28 13:11:58           2019-06-28 13:11:22
2   2019-06-28 13:12:23           2019-06-28 13:11:22
3   2019-06-26 11:14:59           2019-06-26 11:13:38
4   2019-06-26 11:16:04           2019-06-26 11:15:37

Example

DATE_IDENTIFIED                   DATE_CLOSED         days       hours
2019-06-27 10:42:50           2019-09-27 10:40:38        90        0
2019-06-28 13:11:58           2019-06-28 19:11:22         0        6
2019-06-20 13:12:23           2019-06-28 18:11:22         8        5
2019-06-26 11:14:59           2019-06-26 13:13:38         0        2
2019-06-26 11:16:04           2019-06-28 14:15:37         2        3

Perhaps something along the line of the code in this post might get you started:

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

df['C'] = (df['B'] - df['A']).dt.days

For the remaining hours you might need to do some additional math by for instance converting the difference in hours and subtracting the number of days times 24 hours

df['B'] = (df['B'] - df['A']).dt.hours - df['C'] * 24

You need to do:

### first convert your columns to datetime object if it is not already
df['DATE_IDENTIFIED']  = pd.to_datetime(df['DATE_IDENTIFIED'])
df['DATE_CLOSED']  = pd.to_datetime(df['DATE_CLOSED'])

### GET DAYS LIKE THIS
df['days'] = (df['DATE_CLOSED'] - df['DATE_IDENTIFIED']).dt.days

### GET HOURS LIKE THIS
df['hours'] = df['DATE_CLOSED'].dt.hour - df['DATE_IDENTIFIED'].dt.hour

Output:

      DATE_IDENTIFIED         DATE_CLOSED  days  hours
0 2019-06-27 10:42:50 2019-09-27 10:40:38    91      0
1 2019-06-28 13:11:58 2019-06-28 19:11:22     0      6
2 2019-06-20 13:12:23 2019-06-28 18:11:22     8      5
3 2019-06-26 11:14:59 2019-06-26 13:13:38     0      2
4 2019-06-26 11:16:04 2019-06-28 14:15:37     2      3

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