Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the subtracted date value in Python

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.

like image 978
Eseresaure Avatar asked Feb 24 '26 22:02

Eseresaure


1 Answers

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.
like image 187
jpp Avatar answered Feb 26 '26 12:02

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!