Rewrite date utils using match/case

This commit is contained in:
Edward Betts 2024-07-07 11:50:59 +01:00
parent a873060949
commit e7ae7123f6

View file

@ -7,20 +7,24 @@ DateOrDateTime = datetime | date
def as_date(d: DateOrDateTime) -> date:
"""Convert datetime to date."""
if isinstance(d, datetime):
match d:
case datetime():
return d.date()
assert isinstance(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: