gpt4 book ai didi

python - 如何在 Django/Python 中减去两个日期?

转载 作者:IT老高 更新时间:2023-10-28 21:48:24 25 4
gpt4 key购买 nike

我正在开发一个小型健身追踪器,以便自学 Django。我想随着时间的推移绘制我的体重,所以我决定使用 Python Google Charts Wrapper。 Google 图表要求您将日期转换为 x 坐标。为此,我想通过从最后一次称重中减去第一次称重然后使用它来计算 x 坐标来获取我的数据集中的天数(例如,我可以通过结果为 100 并增加x 坐标为每个 y 坐标的结果数。)

无论如何,我需要弄清楚如何将 Django 日期时间对象彼此相减,到目前为止,我在 google 和堆栈中都取得了成功。我知道 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()

关于如何在 View 中进行的任何想法?非常感谢!

最佳答案

您可以直接减去日期,这将产生一个 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

关于python - 如何在 Django/Python 中减去两个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com