Dateutil package: absolute difference in seconds between two dates

I am using Python and 'dateutil'. I have two dates "date1" and "date2" that are parsed from multiple lines:

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

      

How can one get the absolute (non-negative) time difference between 'date1' and 'date2' in seconds? Just one number.

+3


source to share


2 answers


dateutil.parser.parse

returns datetime.datetime

objects that you can subtract from each other to get an object datetime.timedelta

, the difference between two times.

Then you can use the method total_seconds

to get the number of seconds.



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

      

Note that if date1

further in the future than date2

, then the method total_seconds

will return a negative number.

+6


source


Use the method total_seconds()

for temporary 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

      

+2


source







All Articles