使用datetime方法计算工作日

时间:2013-01-21 19:40:46

标签: django django-models django-views

这与我之前提出的一个问题有关..好吧,所以我有一个带有自定义保存方法的模型,它从另一个中减去一个日期并返回“total_days”:

class LeaveRequest(models.Model):
employee = models.ForeignKey(UserProfile)
supervisor = models.ForeignKey(UserProfile, related_name='+', blank=False, null=False)
submit_date = models.DateField(("Date"), default=datetime.date.today)
leave_type = models.CharField(max_length=64, choices=TYPE_CHOICES)
start_date = models.DateField(("Date"))
return_date = models.DateField(("Date"))
total_days = models.IntegerField()
notes = models.TextField(max_length=1000)

def __unicode__ (self):
    return u'%s %s' % (self.employee, self.submit_date)

def save(self, *args, **kwargs):
    self.total_days = (self.return_date - self.start_date).days
    super(LeaveRequest, self).save(*args, **kwargs)

    class Admin: 
            pass

    class Meta:
            ordering = ['-submit_date']

这种方法效果不错,但周末不考虑因素。我如何调整逻辑(在模型中或视图中)以获得“total_days”减去周末天数?

1 个答案:

答案 0 :(得分:0)

您可以使用Python日期时间库。

有关python实现的信息,请参阅this post

from datetime import date, timedelta

...    

def save(self, *args, **kwargs):
    daygenerator = (self.start_date + timedelta(x+1) for x in xrange((
                    self.return_date - self.start_date).days))
    self.total_days = sum(1 for day in daygenerator if day.weekday() < 5)
    super(LeaveRequest, self).save(*args, **kwargs)