相关疑难解决方法(0)

如何计算python中两个日期之间的差异

我试图计算"一年中的几个星期"中两个日期之间的差异.我可以获取datetime对象并获取日期等但不是周数.当然,我不能减去日期,因为周末无法确保.

我尝试使用d1.isocalendar()[1]和减去周数,d2.isocalendar()[1]但问题是isocalendar()[1]返回December 31, 2012第1周(这应该是正确的),但这意味着我的逻辑不能超过这个日期.

作为参考,这是我的完整代码:

def week_no(self):
    ents = self.course.courselogentry_set.all().order_by('lecture_date')
    l_no = 1
    for e in ents:
        if l_no == 1: 
             starting_week_of_year = e.lecture_date.isocalendar()[1] # get week of year
             initial_year = e.lecture_date.year   
        if e == self: 
            this_year = e.lecture_date.year
            offset_week = (this_year - initial_year) * 52
            w_no = e.lecture_date.isocalendar()[1] - starting_week_of_year + 1 + offset_week
            break 
        l_no += 1
    return w_no  
Run Code Online (Sandbox Code Playgroud)

使用此代码,2012年12月31日的讲座最终为-35.

python datetime

29
推荐指数
3
解决办法
3万
查看次数

标签 统计

datetime ×1

python ×1