1

I have Panda dataframe df of following structure, Start and End Time are string values.

           Start Time            End Time
0    2007-07-24 22:00:00    2007-07-25 07:16:53 
1    2007-07-25 07:16:55    2007-07-25 08:52:19 
2    2007-07-25 09:45:53    2007-07-25 10:30:00 
3    2007-07-25 12:32:00    2007-07-25 14:13:38 
4    2007-07-25 22:59:00    2007-07-26 13:43:00

1- How to find the difference in Hours and Minutes between End Time and Start
2- Query the dataframe to filter all rows having time less than 1 hour and 30 minutes
3- Filter all rows having time difference between 20 minutes and 40 minutes

cs95
  • 379,657
  • 97
  • 704
  • 746
Asif Khan
  • 1,228
  • 1
  • 11
  • 22

1 Answers1

2

Question 1
Use pd.to_datetime, and then subtract the columns.

for c in df.columns:
    df[c] = pd.to_datetime(df[c])

(df['End Time'] - df['Start Time']).dt.total_seconds() / 3600

0     9.281389
1     1.590000
2     0.735278
3     1.693889
4    14.733333
dtype: float64

Question 2
Just use a mask and filter:

v = (df['End Time'] - df['Start Time']).dt.total_seconds() / 3600
df[v < 1.5]

           Start Time            End Time
2 2007-07-25 09:45:53 2007-07-25 10:30:00

If I misunderstood, and you actually want to retain such rows, reverse the condition:

df[v >= 1.5]

           Start Time            End Time
0 2007-07-24 22:00:00 2007-07-25 07:16:53
1 2007-07-25 07:16:55 2007-07-25 08:52:19
3 2007-07-25 12:32:00 2007-07-25 14:13:38
4 2007-07-25 22:59:00 2007-07-26 13:43:00

Question 3
Again, use a mask and filter:

df[(1/3 <= v) & (v <= 2/3)]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Question 1 only return hours, I also need minutes in addition to that. Can we solve this by using the attributes of hours and minutes. – Asif Khan Nov 20 '17 at 05:59
  • @AsifKhan Sorry, my mistake. Don't use integer division (Idk why I keep doing that). See my edit. – cs95 Nov 20 '17 at 06:01
  • float division returns number like 1.693889, whole portions is definitely the hours, do we further process the decimal portion to further extract the minutes? Can we solve this using datatime object attributes, e.g. the difference between two datetime object is also a datetime object, can we extract its hours and minute attributes from datetime object? – Asif Khan Nov 20 '17 at 06:13
  • @COLDSPEED your answer solved my problem, i want to upvote your answer but the system do not allow me to upvote because of less than 15 reputation. – Asif Khan Nov 20 '17 at 13:20
  • Oh I understand. I'm beginner here so need some time to understand :D – Asif Khan Nov 21 '17 at 13:18