Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
Modulo datetime
#1
Hola, soy nuevo en la programación, y estoy intentando entender como funcionan las fechas y horas en python, tengo esta situación:
quiero crear una agenda de citas, lo estoy haciendo en django, donde tengo mis modelos, de profesional, servicio (que brinda ese profesional), y como tal el objeto de reserva,
lo que quiero hacer o lo que tengo duda, es:
Ya tengo configurado horario de entrada y salida de un profesional digamos (7 am - 6 pm)
ahora cada servicio tiene un intervalo de tiempo, digamos "servicio1" es de 20 min.
como puedo ocupar con el objeto reserva, ese tiempo en la agenda del "profesional". 
en realidad no entiendo como puedo ocupar espacios de tiempo, dentro de un objeto, para que yo pueda gestionar sus citas.

Les agradezco de antemano, y si alguen le sirve cuando termine puedo conpartirles mis repositorio de git, para que vean como quedo.
muchas gracias.
Responder
#2
Quizas algo asi te de una idea.

Código:
from datetime import datetime, time, timedelta
from typing import List


def get_time(time: str) -> tuple[int, int]:
    hour, minute = time[:-2].split(":")
    period = time[-2:]

    hour = int(hour)
    minute = int(minute)
    if period.strip() == 'pm':
        hour = hour + 12
    return hour, minute


class Service:
    def __init__(self, name: str, time_in_minutes: int):
        self.name = name
        self.time_in_minutes = time_in_minutes

    def __repr__(self) -> str:
        return f"Service name: {self.name} and time in minutes {self.time_in_minutes}"


class Professional:
    def __init__(self, name: str, start_time: str, end_time: str, date_format: str):
        today = datetime.now().date()
        self.name = name
        start_hour, start_minutes = get_time(start_time)
        end_hour, end_minutes = get_time(end_time)
        self.start_time = datetime.combine(
            today, time(start_hour, start_minutes, 0))
        self.end_time = datetime.combine(today, time(end_hour, end_minutes, 0))
        self.date_format = date_format
        self.services: List[Service] = []

    def add_service(self, service: Service):
        total_minutes = self.get_total_service_minutes() + service.time_in_minutes
        if total_minutes > self.total_work_minutes():
            message = f"{total_minutes} minutes will excess the minutes {self.total_work_minutes()} a professional work"
            raise Exception(message)
        self.services.append(service)

    def get_total_service_minutes(self):
        total = 0
        for service in self.services:
            total += service.time_in_minutes
        return total

    def show_services(self) -> List[str]:
        current_services: List[str] = []
        start_time = self.start_time
        for service in self.services:
            current_time = start_time + \
                timedelta(minutes=service.time_in_minutes)
            current_services.append(
                f"Service name: {service.name}. From {start_time} to {current_time.strftime(self.date_format)}")
            start_time = current_time
        return current_services

    def total_work_minutes(self) -> int:
        '''Total amount of minutes the professional works'''
        # Calculate the timedelta
        timedelta = self.end_time - self.start_time

        # Calculate the number of minutes
        return int(timedelta.total_seconds() / 60)

    def __repr__(self) -> str:
        return f"""Professional name: {self.name}. Start time {self.start_time.strftime(self.date_format)}
              and End time {self.end_time.strftime(self.date_format)}.
              Total number of minutes he/she works a day is: {self.total_work_minutes()}.
              Current number of services {len(self.services)}.
              Current total of services minutes: {self.get_total_service_minutes()}"""


if __name__ == "__main__":
    prof = Professional(name='Alberto',
                        start_time="7:30 am",
                        end_time="6:30 pm",
                        date_format="%Y-%m-%d %I:%M:%S %p")

    service1 = Service(name="Service1", time_in_minutes=30)
    service2 = Service(name="Service2", time_in_minutes=45)
    service3 = Service(name="Service3", time_in_minutes=30)
    prof.add_service(service=service1)
    prof.add_service(service=service2)
    prof.add_service(service=service3)

    print()
    print(prof)
    current_services = prof.show_services()
    for service in current_services:
        print(service)

    print("================================")

    # Otro professional
    prof2 = Professional(name='Julian',
                         start_time="7:30 am",
                         end_time="8:45 am",
                         date_format="%Y-%m-%d %I:%M:%S %p")

    prof2.add_service(service=service1)
    prof2.add_service(service=service2)
    # Adding the service below should throw exception because it
    # exceed the number of minutes this professional works a day ...
    # prof2.add_service(service=service3)
    print()
    print(prof2)
    current_services = prof2.show_services()
    for service in current_services:
        print(service)
Responder


Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)