Home > front end >  Compare a date with a time period
Compare a date with a time period

Time:11-17

I'm currently running a zoo. The user is asked for a valid date, if the given date is between the inaccessible period for a given animal the animal's name will not be printed, but if it is ouside the period it will. How do I do this if the the date and the period are strings and how do I compare if the date is within the inaccessible period?

Here is the code:

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")

CodePudding user response:

The datetime module allows for dates to be subtracted, to yield a "delta".

If you subtract your date from the start of the period, and it's before, you know it's outside the range, same with subtracting the end of the period from the entered date.

So all you need to do is

  1. take apart your period strings (hint: string.split does good things!)
  2. convert the end and beginning date strings to dates using the same method you use to enter the dates
  3. calculate the differences between the user-entered date and these boundary dates
  4. check whether they are both positive

CodePudding user response:

If the dates are consistent in the animal, you can inaccessible.split(" - ") to get each date, then do the same you did in the input_date to get the strings to date objects (strptime). Then dates can be compared using operators (>, <, ==).

This will return true if the input date is in between the inaccessible dates (start and end) start_date < input_date < end_date

CodePudding user response:

Convert the inaccessible date strings into datetime objects, similarly to how you did in 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
  • Related