简体   繁体   中英

Django datetime expression

Hello I am using django and am collecting datetime via

start_date = models.DateTimeField('start date', blank=True)
end_date = models.DateTimeField('end date', blank=True)

I have a report start date and a report end date.

I wish to retrieve the time taken for the report by,

taking the end_date and subtracting the end date and rounding it to the nearest day

def report_days(self):
    return self.end_date - self.start_date

currently the python shell returns this

>>> a.report_days()
datetime.timedelta(2, 65020, 613435)

Django represents DateTimeFields as Python datetime objects, so the result of your subtraction is a datetime.timedelta object. To get the number of full days, you can do:

delta = self.end_date - self.pub_date
return delta.days

This only counts full days, though. To round to the nearest full day, you can do something like:

delta = self.end_date - self.pub_date
if delta.seconds / 3600 >= 12:
    return delta.days + 1 # round up
else:
    return delta.days # round down

For more information, see: http://docs.python.org/2/library/datetime.html#timedelta-objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM