How do I subtract two dates in Django/Python?

You can just subtract the dates directly, which will yield a datetime.timedelta object:

dt = weight_now.weight_date - weight_then.weight_date

A timedelta object has fields for days, seconds, and microseconds. From there, you can just do the appropriate math. For example:

hours = dt.seconds / 60 / 60    # Returns number of hours between dates
weeks = dt.days / 7             # number of weeks between dates

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)