我目前正在經營一個動物園。用戶被要求輸入一個有效日期,如果給定的日期在給定動物的不可訪問時間段之間,則不會列印動物的名字,但如果它不在該時間段內,則會列印出來。如果日期和時間段是字串,我該如何執行此操作,以及如何比較日期是否在無法訪問的時間段內?
這是代碼:
def input_date():
while True:
try:
date = input("Enter the date you want to visit us (DD/MM): ")
pattern_date = ('%d/%m')
date = datetime.strptime(date, pattern_date)
except ValueError:
print("Not a valid date, try again")
continue
else:
break
return date
date = input_date()
class animal:
def __init__(self, species, inaccessible):
self.species = species
self.inaccessible = inaccessible
bear = animal("Bear","01/10 - 31/04")
lion = animal("Lion", "01/11 - 28/02")
penguin = animal("Penguin", "01/05 - 31/08")
uj5u.com熱心網友回復:
該datetime模塊允許減去日期,以產生“增量”。
如果您從期間的開始減去您的日期,并且在之前,您就知道它在范圍之外,這與從輸入的日期中減去期間的結束相同。
所以你需要做的就是
- 拆開你的經期字串(提示:
string.split做好事!) - 使用與輸入日期相同的方法將結束和開始日期字串轉換為日期
- 計算用戶輸入的日期和這些邊界日期之間的差異
- 檢查它們是否都是陽性
uj5u.com熱心網友回復:
如果日期在動物中是一致的,您可以inaccessible.split(" - ")獲取每個日期,然后執行您在 中所做的相同操作input_date以獲取日期物件的字串 ( strptime)。然后可以使用運算子 ( >, <, ==)比較日期。
如果輸入日期在不可訪問的日期(開始和結束)之間,這將回傳 true start_date < input_date < end_date
uj5u.com熱心網友回復:
將inaccessible日期字串轉換為datetime物件,類似于您在input_date.
from datetime import datetime
pattern_date = ('%d/%m')
def input_date() -> datetime:
while True:
try:
return datetime.strptime(input(
"Enter the date you want to visit us (DD/MM): "
), pattern_date)
except ValueError:
print("Not a valid date, try again")
class Animal:
def __init__(self, species: str, inaccessible: str):
self.species = species
self._start, self._end = (
datetime.strptime(d, pattern_date)
for d in inaccessible.split(" - ")
)
def is_inaccessible(self, date: datetime) -> bool:
if self._start < self._end:
return self._start <= date <= self._end
else:
return date >= self._start or date <= self._end
animals = [
Animal("Bear", "01/10 - 30/04"),
Animal("Lion", "01/11 - 28/02"),
Animal("Penguin", "01/05 - 31/08"),
]
date = input_date()
available_species = [a.species for a in animals if not a.is_inaccessible(date)]
print(f"Available animals: {', '.join(available_species)}")
Enter the date you want to visit us (DD/MM): 01/06
Available animals: Bear, Lion
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363454.html
