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: def as_date(d: DateOrDateTime) -> date:
"""Convert datetime to date.""" """Convert datetime to date."""
if isinstance(d, datetime): match d:
case datetime():
return d.date() return d.date()
assert isinstance(d, date) case date():
return d return d
case _:
raise TypeError(f"Unsupported type: {type(d)}")
def as_datetime(d: DateOrDateTime) -> datetime: def as_datetime(d: DateOrDateTime) -> datetime:
"""Date/time of event.""" """Date/time of event."""
t0 = datetime.min.time() match d:
return ( case datetime():
d return d
if isinstance(d, datetime) case date():
else datetime.combine(d, t0).replace(tzinfo=timezone.utc) 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: def human_readable_delta(future_date: date) -> str | None: