sourcing/sourcing/utils.py
2023-08-26 17:02:25 -04:00

30 lines
795 B
Python

from datetime import date, datetime, timedelta
import humanize
def display_datetime(dt: datetime) -> str:
"""Render datetime as a string for display."""
if dt is None:
return "n/a"
today = date.today()
if today - dt.date() < timedelta(days=1):
return humanize.naturaltime(dt)
else:
return dt.strftime("%a, %d %b %Y")
def nbsp_at_start(line: str) -> str:
"""Protect spaces at the start of a string."""
space_count = 0
for c in line:
if c != " ":
break
space_count += 1
# return Markup('&nbsp;') * space_count + line[space_count:]
return "\u00A0" * space_count + line[space_count:]
def protect_start_spaces(text: str) -> str:
return "\n".join(nbsp_at_start(line) for line in text.splitlines())