Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - How to calculate difference between two dates in weeks in python

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.

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.

For reference, here's my complete code:

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  

With this code, the lecture on Dec 31, 2012 ends up being -35.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Returns 0 if both dates fall withing one week, 1 if on two consecutive weeks, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...