Difference between dates/times in Python

Asked

Viewed 9,505 times

3

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 so, but when I try to open in other error systems, I want to create a timestamp with the dates but am not getting.

  • 3

    It is working but in other systems it is not? Which systems are these? Explain better, what mistakes are coming up, so it’s hard for anyone to help.

3 answers

6


When you subtract dates in format datetime an object is returned timedelta who has a method total_seconds() 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)

4

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 turn and calculate any difference.

3

Another interesting way to resolve this issue is by using the library dateutil.

That way we can implement the following code:

from datetime import datetime
from dateutil.relativedelta import relativedelta

a = "2015-08-05 08:12:23"
b = "2015-08-09 08:12:23"
f = "%Y-%m-%d %H:%M:%S"

ini = datetime.strptime(a, f)
fim = datetime.strptime(b, f)

di = abs(relativedelta(ini, fim))

print(f'{di.years} anos, {di.months} meses, {di.days} dias, {di.hours} horas, '
      f'{di.minutes} minutos e {di.seconds} segundos.')

Note that the code receives two dates and times in type string, converts them into objects datetime, and then - with the help of the method relativedelta - calculates the difference.

Note also that the result of this method consists of a tuple, with which we can later retrieve each of its elements.

The result of print() is nothing more than the values of each element of the previously generated tuple.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.