0

If given a year-week range e.g, start_year, start_week = (2019,45) and end_year, end_week = (2020,15)

In python how can I check if Year-Week of interest is within the above range of not? For example, for Year = 2020 and Week = 5, I should get a 'True'.

rsk
  • 41
  • 2

3 Answers3

1

Assuming all Year-Week pairs are well-formed (so there's no such thing as (2019-74) you can just check with:

start_year_week = (2019, 45)
end_year_week = (2020, 15)
under_test_year_week = (2020, 5)

in_range = start_year_week <= under_test_year_week < end_year_week  # True

Python does tuple comparison by first comparing the first element, and if they're equal then compare the second and so on. And that is exactly what you want even without treating it as actual dates/weeks :D (using < or <= based on whether you want (2019, 45) or (2020, 15) to be included or not.)

Faboor
  • 1,365
  • 2
  • 10
  • 23
0

You can parse year and week to a datetime object. If you do the same with your test-year /-week, you can use comparison operators to see if it falls within the range.

from datetime import datetime

start_year, start_week = (2019, 45) 
end_year, end_week = (2020, 15)

# start date, beginning of week
date0 = datetime.strptime(f"{start_year} {start_week} 0", "%Y %W %w")
# end date, end of week
date1 = datetime.strptime(f"{end_year} {end_week} 6", "%Y %W %w")

testyear, testweek = (2020, 5)
testdate = datetime.strptime(f"{testyear} {testweek} 0", "%Y %W %w")

date0 <= testdate < date1
# True
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
-1
start = (2019, 45)
end = (2020, 15)


def isin(q):
    if end[0] > q[0] > start[0]:
        return True
    elif end[0] == q[0]:
        if end[1] >= q[1]:
            return True
        else:
            return False
    elif q[0] == start[0]:
        if q[1] >= start[1]:
            return True
        else:
            return False
    else:
        return False

Try this: print(isin((2020, 5))) >>>>> True

Kevin Omar
  • 127
  • 9