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.
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
timedelta.total_seconds().sum and use a generator expression.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With