[英]How can I check if the date lies between two dates coming from loop
我被困在一個點上,我試圖檢查日期是否在兩個日期之間,日期來自帶有 for 循環的 python 的對象。
Date_from 是開始日期,例如01-04-2021
date_to 是結束日期,例如05-04-2021
check_in 是我要檢查的日期,例如03-04-2021
Python代碼:
if check_in.date() in ((d.date_from.date() for d in holidays) < ((d.date_to.date() for d in holidays))):
print("date is in between")
else:
print("Not in between")
我也嘗試過這段代碼,但沒有成功。
if check_in.date() in ((d.date_from.date() for d in holidays) or ((d.date_to.date() for d in holidays))):
print("date is in between")
else:
print("Not in between")
這里指的是這個URL 源來檢查日期位於兩個日期之間我收到此錯誤。
TypeError:“生成器”和“生成器”的實例之間不支持“<”
誰能指導我如何檢查它?
您可以使用any
來測試holydays
的任何元素是否匹配:
any(d.date_from.date()<=check_in.date()<d.date_to.date() for d in holidays)
如果我理解正確,您正在嘗試執行以下操作:
for each holiday
is the checkin date between the holiday start date and the holiday end date
請注意我是如何完全用文字來寫這個描述的。 我使用類似於代碼的格式,因為我有點超前思考,但重要的部分是用文字描述解決方案問題,而不用擔心 python 語法。
現在我們可以將這些詞翻譯成代碼:
# for each holiday
for d in holidays:
# is the checkin date between the holiday start date and the holiday end date
if d.date_from < check_in < d.date_to:
print("in between")
else:
print("not in between")
我認為您最初的嘗試是嘗試一次檢查所有日期。 相反,您需要遍歷假期列表並一次檢查一個日期。
我認為這應該做你想做的事:
from datetime import date
def convert_date(string_date):
"""Takes string date in format dd-mm-yyyy and returns a list of integers in format [yyyy, mm, dd]"""
return reversed(list(map(int, string_date.split('-'))))
# Create check in date object
check_in_obj = date(*convert_date('03-04-2021'))
for d in holidays:
# set date obj for date_from and date_to
date_from_obj = date(*convert_date(d.date_from.date()))
date_to_obj = date(*convert_date(d.date_to.date()))
if date_from_obj <= check_in_obj <= date_to_obj:
print("date is in between")
break
else:
print("Not in between")
然而,這假設了幾件事:
.date()
所返回的內容。 所以我制作了一個小的 function 用於將您的字符串日期轉換為可用於制作datetime.date
對象的整數列表。 然后,將您的日期作為date
對象,您只需比較上面鏈接的答案中顯示的日期即可。
請注意,最后一個else
語句用於for
循環。
讓我知道這是否適合您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.