From e7ae7123f623fba6e1baa4482b5b22b101ac1a9a Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Sun, 7 Jul 2024 11:50:59 +0100 Subject: [PATCH] Rewrite date utils using match/case --- agenda/utils.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/agenda/utils.py b/agenda/utils.py index 1b03fc3..ff311d0 100644 --- a/agenda/utils.py +++ b/agenda/utils.py @@ -7,20 +7,24 @@ DateOrDateTime = datetime | date def as_date(d: DateOrDateTime) -> date: """Convert datetime to date.""" - if isinstance(d, datetime): - return d.date() - assert isinstance(d, date) - return d + match d: + case datetime(): + return d.date() + case date(): + return d + case _: + raise TypeError(f"Unsupported type: {type(d)}") def as_datetime(d: DateOrDateTime) -> datetime: """Date/time of event.""" - t0 = datetime.min.time() - return ( - d - if isinstance(d, datetime) - else datetime.combine(d, t0).replace(tzinfo=timezone.utc) - ) + match d: + case datetime(): + return d + case date(): + return datetime.combine(d, datetime.min.time()).replace(tzinfo=timezone.utc) + case _: + raise TypeError(f"Unsupported type: {type(d)}") def human_readable_delta(future_date: date) -> str | None: