Difference between dates / times in Python

2

I need to calculate the difference between two dates in python, but always some error.

>>> from datetime import datetime
>>> data1 = datetime(2015, 8, 5, 8, 12, 23)
>>> data2 = datetime(2015, 8, 9, 6, 13, 23)
>>> difdata = data2 - data1
>>> '{0}:{2}'.format(*str(difdata).split())
'3:22:01:00'

I want to do this, but when I try to open in other error systems, I want to create a timestamp with the dates but I'm not getting it.

    
asked by anonymous 13.08.2015 / 21:10

2 answers

2

I found a solution by searching the DATETIME function

s = '2015/08/05 08:12:23'
t = '2015/08/09 08:13:23'

date1 = int(datetime.datetime.strptime(s, '%d/%m/%Y %H:%M:%S').strftime("%s"))
date2 = int(datetime.datetime.strptime(t, '%d/%m/%Y %H:%M:%S').strftime("%s"))

difdate = date2 - date1

print(difdate)

So it's easy to transform and calculate any difference.

    
14.08.2015 / 22:48
2

When you subtract dates in the format datetime a timedelta object is returned that has a total_seconds() method that gives you the total seconds:

from datetime import datetime
s = '2015/08/05 08:12:23'
t = '2015/08/09 08:13:23'
f = '%Y/%m/%d %H:%M:%S'
dif = (datetime.strptime(t, f) - datetime.strptime(s, f)).total_seconds()
print(dif)
    
15.08.2015 / 00:43