Search code examples
pythondatedatetime

Dates difference in days as a fraction


I have two dates (datetime objects) which I want to subtract from each other. The result I am expecting is the number of days between the two. This is how I am doing it:

def get_days_between(datePast, dateFuture):
   difference = dateFuture - datePast
   return difference.days

The problem is, I need the number of days as a fraction. Example: If the past and future dates are only 12 hours apart, I am expecting the result to be 0.5 day.

How can I achieve that ?


Solution

  • from datetime import timedelta
    
    def get_days_between(datePast, dateFuture):
       difference = dateFuture - datePast
       return difference.total_seconds() / timedelta(days=1).total_seconds()