Python,JSON如何检查用户选择的时间是否已被其他人预订?

txu3uszq  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(137)

我有2个CSV和JSON文件:

name, start_time, end_time
Michał Najman, 23.03.2023 14:00, 23.03.2023 15:00
Marcin Wiśniewski, 23.03.2023 17:00, 23.03.2023 18:00
Tadeusz Stockinger, 24.03.2023 11:00, 24.03.2023 12:30
Robert Brzozowski, 24.03.2023 12:30, 24.03.2023 14:00
Norman Dudziuk, 24.03.2023 16:30, 24.03.2023 17:00
Klaus Sevkovic, 25.03.2023 14:00, 25.03.2023 14:30
Paweł Gulczyński, 26.03.2023 12:00, 26.03.2023 13:30
Mieczysław Okniński, 26.03.2023 13:30, 26.03.2023 14:00

Json:

{"23.03": [{
  "name": "Michał Najman",
  "start_time": "14:00",
  "end_time": "15:00"
},
{"name": "Marcin Wiśniewski",
  "start_time": "17:00",
  "end_time": "18:00"
}],
  "24.03": [{
  "name": "Tadeusz Stockinger",
  "start_time": "11:00",
  "end_time": "12:30"
},
{"name": "Robert Brzozowski",
  "start_time": "12:30",
  "end_time": "14:00"
},
  {"name": "Norman Dudziuk",
  "start_time": "16:30",
  "end_time": "17:00"
}],
    "25.03": [{
  "name": "Klaus Sevkovic",
  "start_time": "14:00",
  "end_time": "14:30"
}],
    "26.03": [{
  "name": "Paweł Gulczyński",
  "start_time": "12:00",
  "end_time": "13:30"
},
{"name": "Mieczysław Okniński",
  "start_time": "13:30",
  "end_time": "14:00"
}],
    "27.03": [],
    "28.03": [],
    "29.03": [],
    "30.03": []
}

我试着检查JSON文件中的时间是否可用,如果用户选择的时间不可用,程序应该建议下一个时间,例如:您想预订16:00的房间吗?答案:(是/否)
如果用户选择No,请返回上一步。我正在阅读一个JSON文件,并尝试检查我想要的时间是否可用,如果没有,则我会问用户是否要预订下午4点?(yes/no)#如果用户选择No,请返回上一步。

import json

class Make_aReservation:
    # print('$ Make a reservation ')
    # name = input("What's your Name?\n")
    book = input("When would you like to book? {DD.MM.YYYY HH:MM}\n")

    def __init__(self):
        self.filename = '23.03-30.03.json'

    def file_to_text(self):
        with open(self.filename, "r") as file_opened:
            text = json.load(file_opened)
            return text

    def reservation(self):
        # print(self.file_to_text())
        if self.book[:5] in self.file_to_text():
            # print(self.file_to_text()[self.book[:5]])
            # print(self.file_to_text()[self.book[:5]])
            for i in self.file_to_text()[self.book[:5]]:
                print(i)
                print(self.book[11:16])
                if self.book[11:16] in i['end_time']:
                    print(True)
                else:
                    print(False)

make_aReservation = Make_aReservation()
print(make_aReservation.reservation())

输出:

When would you like to book? {DD.MM.YYYY HH:MM}
23.03.2023 15:00
{'name': 'Michał Najman', 'start_time': '14:00', 'end_time': '15:00'}
15:00
True
{'name': 'Marcin Wiśniewski', 'start_time': '17:00', 'end_time': '18:00'}
15:00
False
None

Process finished with exit code 0

如何检查这样的JSON文件是否已经预订?

bxgwgixi

bxgwgixi1#

from datetime import datetime, timedelta

class ReservationSystem:
    def __init__(self):
        self.reservations = {}  # empty dictionary to store reservations

    def make_reservation(self):
        name = input("What's your name? ")
        reservation_time = input("When would you like to book? (DD.MM.YYYY HH:MM) ")
        reservation_time = datetime.strptime(reservation_time, "%d.%m.%Y %H:%M")

        # check if the date is less than 1 hour from now
        if reservation_time < datetime.now() + timedelta(hours=1):
            print("Reservation time should be at least 1 hour from now.")
            return

        # check if the user has more than 2 reservations already this week
        reservations_this_week = [r for r in self.reservations.values() if
                                  r['name'] == name and r['start_time'].isocalendar()[1] ==
                                  reservation_time.isocalendar()[1]]
        if len(reservations_this_week) >= 2:
            print("You cannot have more than 2 reservations this week.")
            return

        # check if the court is already reserved for the time user specified
        reservation_date = reservation_time.strftime("%d.%m.%Y")
        if reservation_date in self.reservations:
            for r in self.reservations[reservation_date]:
                if r['start_time'] <= reservation_time < r['end_time']:
                    print(
                        f"The court is already reserved from {r['start_time'].strftime('%H:%M')} to"
                        f" {r['end_time'].strftime('%H:%M')}.")
                    suggest_reservation_time = r['end_time'] + timedelta(minutes=30)
                    suggest_reservation_time = suggest_reservation_time.replace(second=0, microsecond=0)
                    make_suggestion = input(
                        f"Would you like to make a reservation for {suggest_reservation_time.strftime('%H:%M')} "
                        f"instead? (yes/no) ")
                    if make_suggestion.lower() == "yes":
                        reservation_time = suggest_reservation_time
                    else:
                        return

        # display possible periods in 30 minute intervals up to 90 minutes
        start_time = reservation_time.replace(minute=0, second=0, microsecond=0)
        end_time = start_time + timedelta(minutes=90)
        available_periods = []
        for i in range(1, 4):
            if start_time + timedelta(minutes=30 * i) <= end_time:
                available_periods.append(
                    f"{i}) {start_time.strftime('%H:%M')} - {(start_time + timedelta(minutes=30 * i)).strftime('%H:%M')}")
        print("How long would you like to book court?")
        print("\n".join(available_periods))
        choice = input("Enter your choice (1-3): ")
        while not choice.isdigit() or int(choice) not in range(1, 4):
            choice = input("Invalid choice. Enter your choice (1-3): ")
        duration = int(choice) * 30

        # add the reservation to the dictionary
        if reservation_date not in self.reservations:
            self.reservations[reservation_date] = []
        self.reservations[reservation_date].append({
            'name': name,
            'start_time': reservation_time,
            'end_time': reservation_time + timedelta(minutes=duration)
        })
        print(
            f"Reservation made for {name} on {reservation_time.strftime('%d.%m.%Y')} from {reservation_time.strftime('%H:%M')} to {(reservation_time + timedelta(minutes=duration)).strftime('%H:%M')}.")
        # cheack
        print(self.reservations)

    def cancel_reservation(self):
        print("Cancel a reservation")
        name = input("What's your name? ")
        reservation_time = input("When was your reservation? (DD.MM.YYYY HH:MM) ")
        reservation_time = datetime.strptime(reservation_time, "%d.%m.%Y %H:%M")

        # check if the date is less than 1 hour from now
        if reservation_time < datetime.now() + timedelta(hours=1):
            print("You cannot cancel a reservation less than 1 hour from now.")
            return

        # check if the reservation exists
        reservation_date = reservation_time.strftime("%d.%m.%Y")
        if reservation_date not in self.reservations:
            print(f"No reservations found for {reservation_date}.")
            return
        reservation_exists = False
        for r in self.reservations[reservation_date]:
            if r['name'] == name and r['start_time'] == reservation_time:
                reservation_exists = True
                break
        if not reservation_exists:
            print(
                f"No reservations found for {name} at {reservation_time.strftime('%H:%M')} on {reservation_date}.")
            return

        # remove the reservation
        self.reservations[reservation_date] = [r for r in self.reservations[reservation_date] if
                                               not (r['name'] == name and r['start_time'] == reservation_time)]
        print(f"Reservation for {name} at {reservation_time.strftime('%H:%M')} on {reservation_date} cancelled.")
        # check
        print(self.reservations)

    def print_schedule(self):
        start_date = input("Enter start date (DD.MM.YYYY): ")
        start_date = datetime.strptime(start_date, "%d.%m.%Y")
        end_date = input("Enter end date (DD.MM.YYYY): ")
        end_date = datetime.strptime(end_date, "%d.%m.%Y")

        delta = end_date - start_date

        for i in range(delta.days + 1):
            day = start_date + timedelta(days=i)
            reservations = self.reservations.get(day.strftime("%d.%m.%Y"), [])

            if len(reservations) == 0:
                print(day.strftime("%A") + ": No Reservations")
            else:
                print(day.strftime("%A") + ":")
                for r in reservations:
                    print(
                        f"* {r['name']} {r['start_time'].strftime('%d.%m.%Y - %H:%M')} - {r['end_time'].strftime('%H:%M')}")

# example usage
rs = ReservationSystem()
rs.make_reservation()
rs.cancel_reservation()
rs.print_schedule()

相关问题