如何在python中计算两个日期之间的差异 [英] How to calculate difference between two dates in weeks in python
问题描述
我正在计算一年中的几个星期的两个日期之间的差异。我可以得到datetime对象,并获取日期等,但不能得到周数。当然,我不能减去日期,因为周末不能保证。
I'm trying to calculate the difference between two dates in "weeks of year". I can get the datetime object and get the days etc but not week numbers. I can't, of course, subtract dates because weekends can't be ensured with that.
我尝试使用 d1.isocalendar()[1]
并减去 d2.isocalendar()[1]
但问题是 isocalendar()[1]
返回 2012
作为第1周(据说是正确的),但这意味着我的逻辑不能跨过这个日期。
I tried getting the week number using d1.isocalendar()[1]
and subtracting d2.isocalendar()[1]
but the issue is that isocalendar()[1]
returns December 31, 2012
as week 1 (which supposedly is correct) but that means my logic cannot span over this date.
以下是我的完整代码:
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
有了这段代码,2012年12月31日的演讲结束了是-35。
With this code, the lecture on Dec 31, 2012 ends up being -35.
推荐答案
在相应日期的几周内计算星期一之间的星期差异如何?在以下代码中, monday1
是 d1
(同一周)之前的星期一:
How about calculating the difference in weeks between the Mondays within weeks of respective dates? In the following code, monday1
is the Monday on or before d1
(the same week):
from datetime import datetime, timedelta
monday1 = (d1 - timedelta(days=d1.weekday()))
monday2 = (d2 - timedelta(days=d2.weekday()))
print 'Weeks:', (monday2 - monday1).days / 7
如果两个日期下降一周, 0 1 周等。
Returns 0 if both dates fall withing one week, 1 if on two consecutive weeks, etc.
这篇关于如何在python中计算两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!