Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I subtract two dates in Django/Python?

I'm working on a little fitness tracker in order to teach myself Django. I want to graph my weight over time, so I've decided to use the Python Google Charts Wrapper. Google charts require that you convert your date into a x coordinate. To do this I want to take the number of days in my dataset by subtracting the first weigh-in from the last weigh-in and then using that to figure out the x coords (for example, I could 100 by the result and increment the x coord by the resulting number for each y coord.)

Anyway, I need to figure out how to subtract Django datetime objects from one another and so far, I am striking out on both google and here at the stack. I know PHP, but have never gotten a handle on OO programming, so please excuse my ignorance. Here is what my models look like:

class Goal(models.Model):     goal_weight = models.DecimalField("Goal Weight",          max_digits=4,          decimal_places=1)     target_date = models.DateTimeField("Target Date to Reach Goal")     set_date = models.DateTimeField("When did you set your goal?")     comments = models.TextField(blank=True)      def __unicode__(self):         return unicode(self.goal_weight)  class Weight(models.Model):     """ Weight at a given date and time. """      goal = models.ForeignKey(Goal)     weight = models.DecimalField("Current Weight",         max_digits=4,          decimal_places=1)     weigh_date = models.DateTimeField("Date of Weigh-In")     comments = models.TextField(blank=True)      def __unicode__(self):         return unicode(self.weight)      def recorded_today(self):         return self.date.date() == datetime.date.today() 

Any ideas on how to proceed in the view? Thanks so much!

like image 456
biased_estimator Avatar asked May 18 '10 23:05

biased_estimator


People also ask

Can you subtract two datetime objects?

Subtraction of two datetime objects in Python:It is allowed to subtract one datetime object from another datetime object. The resultant object from subtraction of two datetime objects is an object of type timedelta.

How do you subtract two date objects in python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1.

How do you subtract two date columns?

Step 1: In cell C2, use a usual subtraction method to subtract the First Date from the Second Date. Use the formula as =B2-A2. Step 2: Select the entire column C and click on the Home tab under the Number group section; select either General or Number formatting through the dropdown list to convert it into numbers.


2 Answers

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 
like image 115
mipadi Avatar answered Sep 20 '22 08:09

mipadi


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 
like image 41
Dan Head Avatar answered Sep 18 '22 08:09

Dan Head