简体   繁体   中英

Python - Getting week number from date and viceversa not corresponding

I have the following problem: from a given date I need to find the week number of that year and then find the start day and end day of that week.

day1= datetime.datetime(2015,9,28)
day2= datetime.datetime(2017,12,18)

finding the week works fine:

day1.isocalendar()
day2.isocalendar()

returns

(2015, 40, 1)
(2017, 51, 1)

Which also corresponds with some standard calendars: http://whatweekisit.org/calendar-2015.html

Then I defined the following function:

def week_start_end(year,week):
    '''Given year and week, returns the start and end day of the week
as datetime object'''
    w = "%s-W%s"%(year,week)
    s = datetime.datetime.strptime(w + '-1', "%Y-W%W-%w")#monday
    e= datetime.datetime.strptime(w + '-0', "%Y-W%W-%w")#sunday
    return (s,e)

when I call it with the year and week as arguments:

week_start_end(2015,40)
week_start_end(2017,51)

returns the following:

(datetime.datetime(2015, 10, 5, 0, 0), datetime.datetime(2015, 10, 11, 0, 0))
(datetime.datetime(2017, 12, 18, 0, 0), datetime.datetime(2017, 12, 24, 0, 0))

As you can see, it is working well for the 2nd date, but not for the first. Trying several instances, I have realised that this function always returns one week later than it should for 2015, but gets it right for 2016 and 2017.

I could not find my way through it. Can you help me please?

Different week numbering conventions. The week number you get with %W is not the same as the ISO week number. I believe that you can get ISO week numbers with %V, but I have not tried it and it seems to be platform dependent.

Why not use the library isoweek

from isoweek import Week

def week_start_end(year, week):
    '''Given year and week, returns the start and end day of the week
as datetime object'''
    w = Week(year, week)
    s = w.monday()
    e = w.sunday()
    return (s,e)

And finally

>>> week_start_end(2015, 40)
(datetime.date(2015, 9, 28), datetime.date(2015, 10, 4))
>>> week_start_end(2017, 51)
(datetime.date(2017, 12, 18), datetime.date(2017, 12, 24))

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