The Python Oracle

what would be the pythonic way to find out if a given date belongs to the current week?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping

--

Chapters
00:00 What Would Be The Pythonic Way To Find Out If A Given Date Belongs To The Current Week?
01:02 Accepted Answer Score 15
01:43 Thank you

--

Full question
https://stackoverflow.com/questions/3716...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 15


You can use the isodate method for datetime objects:

datetime.datetime.strptime('20160511','%Y%m%d').isocalendar()[1]

It will return the current week as an integer, so that you can compare two dates to see if they're part of the same week. Here is a function that would do that for two different dates:

import datetime

def same_week(date1, date2):
    d1 = datetime.datetime.strptime(date1,'%Y%m%d')
    d2 = datetime.datetime.strptime(date2,'%Y%m%d')
    return d1.isocalendar()[1] == d2.isocalendar()[1] \
              and d1.year == d2.year

To get the current day, use datetime.datetime.today(). So, rewriting the above function to do exactly what you're asking:

import datetime

def same_week(dateString):
    '''returns true if a dateString in %Y%m%d format is part of the current week'''
    d1 = datetime.datetime.strptime(dateString,'%Y%m%d')
    d2 = datetime.datetime.today()
    return d1.isocalendar()[1] == d2.isocalendar()[1] \
              and d1.year == d2.year