简体   繁体   English

检查给定的年周是否在年周范围内

[英]Check if given Year-Week is within Year-Week Range

If given a year-week range eg, start_year, start_week = (2019,45) and end_year, end_week = (2020,15)如果给定年周范围,例如 start_year, start_week = (2019,45) 和 end_year, end_week = (2020,15)

In python how can I check if Year-Week of interest is within the above range of not?在 python 中,我如何检查感兴趣的年周是否在上述范围内? For example, for Year = 2020 and Week = 5, I should get a 'True'.例如,对于 Year = 2020 和 Week = 5,我应该得到一个“真”。

Assuming all Year-Week pairs are well-formed (so there's no such thing as (2019-74) you can just check with:假设所有年-周对都是格式良好的(所以没有(2019-74)这样的东西,你可以检查一下:

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. Python 通过首先比较第一个元素进行元组比较,如果它们相等,则比较第二个元素,依此类推。 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.)这正是您想要的,即使不将其视为实际日期/周:D(使用<<=根据您是否希望(2019, 45)(2020, 15)包含在内。)

You can parse year and week to a datetime object.您可以将年和周解析为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
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试试这个: print(isin((2020, 5))) >>>>> True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM