69
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
37
Django datetime
objects are just regular Python datetime
objects. When you subtract one datetime
from another you get a timedelta
object.
If you are looking to subtract a length of time from a datetime
you need to subtract a timedelta
object from it. For example:
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> print now
2010-05-18 23:16:24.770533
>>> this_time_yesterday = now - timedelta(hours=24)
>>> print this_time_yesterday
2010-05-17 23:16:24.770533
>>> (now - this_time_yesterday).days
1
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
- [Django]-Additional field while serializing django rest framework
- [Django]-Django Model MultipleChoice
5
Note that subtracting will not work in case the two date times have different offset-awareness, e.g., one with tzinfo and one without (native).
- [Django]-How do I display the value of a Django form field in a template?
- [Django]-How to change status of JsonResponse in Django
- [Django]-ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0
Source:stackexchange.com