earlyadopter
earlyadopter

Reputation: 1547

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

I have strings in the "%Y%m%d" format (i.e., "20160511" for today, May 11, 2016). And need to find out programmatically (in python) if another date (let's say – "20160504" or "20160512") send as a parameter to the function belong to the current week (current being today the week started on Sunday, May 8, 2016 – let's assume it's an american way of the week, starting on Sunday, i.e., the first should return False, the second – True).

All ideas I came up with comes to calculating the date of that Sunday, and comparing the passed as a parameter to it, and then, if the day is in the future, that it's not after the Saturday of the current week, but it doesn't look elegant (or "pythonic") enough.

Upvotes: 6

Views: 4506

Answers (1)

rofls
rofls

Reputation: 5115

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    

Upvotes: 15

Related Questions