我正在研究一个小健身追踪器,以便自学Django。我希望随着时间的推移绘制我的体重图,所以我决定使用Python Google Charts Wrapper。 Google图表要求您将日期转换为x坐标。要做到这一点,我想通过从最后一次称重中减去第一次称重然后使用它来计算x坐标来获取数据集中的天数(例如,我可以通过结果得到100并增加x coord每个y坐标的结果数。)
无论如何,我需要弄清楚如何从彼此中减去Django日期时间对象,到目前为止,我正在谷歌和堆栈中罢工。我知道PHP,但从来没有掌握OO编程,所以请原谅我的无知。这是我的模型的样子:
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()
关于如何在视图中进行的任何想法?非常感谢!
答案 0 :(得分:59)
您可以直接减去日期,这将产生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
答案 1 :(得分:33)
Django datetime
个对象只是常规Python datetime
objects。当您从另一个datetime
中减去一个datetime
时,会得到timedelta
个对象。
如果您要从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
个对象。例如:
{{1}}
答案 2 :(得分:4)
请注意,如果两个日期时间具有不同的偏移感知,则减法将不起作用,例如,一个使用tzinfo,一个不使用(本机)。