2010-05-18 70 views
30

我为了教自己的Django工作的一个小健身追踪器。我想随时间推移我的体重,所以我决定使用Python Google Charts Wrapper。 Google图表要求您将日期转换为x坐标。要做到这一点,我想通过减去对我的数据集的天数第一称重从上次称重,然后使用该弄清楚X COORDS(例如,我可以通过结果100和递增x坐标由每个y坐标的结果数)如何减去两个日期在Django/Python的?

无论如何,我需要弄清楚如何从另一个中减去Django日期时间对象,并且到目前为止,我在谷歌和这里都在堆栈上敲出来。我知道PHP,但从来没有掌握面向对象编程,所以请原谅我的无知。以下是我的模型的样子:

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() 

有关如何在视图中继续的任何想法?非常感谢!

回答

54

您可以只需直接减去日期,这将产生一个datetime.timedelta对象:

dt = weight_now.weight_date - weight_then.weight_date 

一个timedelta对象有好几天,秒,毫秒领域。从那里,你可以做适当的数学。例如:

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

完美,非常感谢。几乎逐字地使用了这个。 – 2010-05-19 12:01:47

31

Django的datetime对象只是普通Python datetime objects。当你从另一个减去一个datetime你得到一个timedelta对象。

如果您想从datetime中减去一段时间,则需要从中减去timedelta对象。例如:

>>> 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 
+0

这是伟大的。非常感谢......我很习惯用字符串思考,我不认为可以通过减去另外两个对象来生成对象。 – 2010-05-19 12:01:22

3

注意,减去将不工作的情况下两个日期时代有不同的偏移意识,例如,一个具有tzinfo和一个没有(本机)。

+0

这不是问题的答案。如果你有什么可以添加到已经说过的话,请对另一个答案留言 – FistOfFury 2017-12-31 17:35:02