3

I have a data set of dates:

(u'x', datetime.datetime(2018, 1, 5, 4, 49, 30))
(u'y', datetime.datetime(2018, 1, 5, 9, 59, 10))
(u'x', datetime.datetime(2018, 1, 13, 10, 23, 17))
(u'y', datetime.datetime(2018, 1, 15, 17, 16, 34))
(u'x', datetime.datetime(2018, 1, 22, 11, 9, 55))
(u'y', datetime.datetime(2018, 1, 22, 14, 24, 59))

Here is my code to subtract the date:

for x in range(len(y)):
    if y[x][0] == 'x' and y[x+1][0] != 'y':
        #subtract the date
        print y[x+1][1] - y[x][1]

The code above prints below:

5:09:40
2 days, 6:53:17
3:15:04

My question is how do I add them all up and convert them as total in hours? Appreciate the help on this.

1 Answer 1

1

This is one way.

import datetime

lst = [(u'x', datetime.datetime(2018, 1, 5, 4, 49, 30)),
       (u'y', datetime.datetime(2018, 1, 5, 9, 59, 10)),
       (u'x', datetime.datetime(2018, 1, 13, 10, 23, 17)),
       (u'y', datetime.datetime(2018, 1, 15, 17, 16, 34)),
       (u'x', datetime.datetime(2018, 1, 22, 11, 9, 55)),
       (u'y', datetime.datetime(2018, 1, 22, 14, 24, 59))]

res = sum((y[1]-x[1]).total_seconds()/(60**2) for x, y in zip(lst[::2], lst[1::2]))

# 63.30027777777778

Explanation

  1. Convert to seconds via timedelta.total_seconds().
  2. Then convert to hours by dividing by 60**2.
  3. Finally, wrap in sum and use a generator expression.
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible not to use a generator as an example? Sometimes the data might not be sequential(like 'x' then 'y' seq) that's why I included a check for 'x' overall this makes sense but I hope to use my code above.
Sure, just output the list [(y[1]-x[1]).total_seconds()/(60**2) for x, y in zip(lst[::2], lst[1::2])]. sum also accepts a list, so you can sum later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.