如何在Django/Python中计算两个日期的差值?

42 投票
3 回答
56622 浏览
提问于 2025-04-15 22:52

我正在做一个小的健身追踪器,目的是为了学习Django。我想要绘制我的体重变化图,所以我决定使用Python的Google Charts库。Google Charts需要把日期转换成x坐标。为此,我想通过把第一次称重的日期减去最后一次称重的日期,来计算数据集中的天数,然后用这个结果来确定x坐标(比如,我可以把结果乘以100,然后对每个y坐标增加这个结果的值)。

不过,我需要弄清楚如何在Django中相互减去日期时间对象,但到目前为止,我在谷歌和这里的StackOverflow上都没有找到答案。我会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()

有什么建议可以在视图中继续吗?非常感谢!

3 个回答

5

请注意,如果两个日期时间的时区信息不同,比如一个有时区信息(tzinfo),而另一个没有(本地时间),那么直接相减是行不通的。

37

Django中的datetime对象其实就是普通的Python datetime对象。当你把一个datetime对象减去另一个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
69

你可以直接把两个日期相减,这样会得到一个 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

撰写回答