Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dateutil package: absolute difference in seconds between two dates [duplicate]

I use Python and 'dateutil' package. I have two dates 'date1' and 'date2' that are parsed from some strings:

import dateutil.parser
date1 = dateutil.parser.parse(string1,fuzzy=True)
date2 = dateutil.parser.parse(string2,fuzzy=True)

How is it possible to get absolute (non-negative) time difference between 'date1' and 'date2' in seconds? Just one number.

like image 238
Konstantin Avatar asked Oct 13 '25 00:10

Konstantin


2 Answers

dateutil.parser.parse returns datetime.datetime objects which you can subtract from each other to get a datetime.timedelta object, the difference between two times.

You can then use the total_seconds method to get the number of seconds.

diff = date2 - date1
print(diff.total_seconds())

Note that if date1 is further in the future than date2 then the total_seconds method will return a negative number.

like image 115
Ffisegydd Avatar answered Oct 14 '25 13:10

Ffisegydd


Use the total_seconds() method on a time delta:

import dateutil.parser
from datetime import datetime

date1 = datetime.now()
date2 = dateutil.parser.parse('2013-11-12 09:00:00',fuzzy=True)

>>> print abs((date1 - date2).total_seconds())
25711599.6705
like image 35
mhawke Avatar answered Oct 14 '25 12:10

mhawke