python 两个日期相减_在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!

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值