pferd/PFERD/ilias/date_demangler.py

52 lines
1.5 KiB
Python
Raw Normal View History

2020-04-22 12:44:41 +02:00
"""
Helper methods to demangle an ILIAS date.
"""
import datetime
import locale
2020-04-30 12:00:21 +02:00
import logging
2020-04-22 12:44:41 +02:00
import re
2020-04-30 12:00:21 +02:00
from typing import Optional
2020-04-22 12:44:41 +02:00
2020-04-30 12:00:21 +02:00
from ..logging import PrettyLogger
2020-04-22 12:44:41 +02:00
2020-04-30 12:00:21 +02:00
LOGGER = logging.getLogger(__name__)
PRETTY = PrettyLogger(LOGGER)
def demangle_date(date: str) -> Optional[datetime.datetime]:
2020-04-22 12:44:41 +02:00
"""
Demangle a given date in one of the following formats:
"Gestern, HH:MM"
"Heute, HH:MM"
2020-04-30 12:00:21 +02:00
"Morgen, HH:MM"
2020-04-22 12:44:41 +02:00
"dd. mon.yyyy, HH:MM
"""
saved = locale.setlocale(locale.LC_ALL)
try:
try:
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
except locale.Error:
PRETTY.warning(
"Could not set language to german. Assuming you use english everywhere."
)
2020-04-22 12:44:41 +02:00
date = re.sub(r"\s+", " ", date)
date = re.sub("Gestern|Yesterday", _yesterday().strftime("%d. %b %Y"), date, re.I)
date = re.sub("Heute|Today", datetime.date.today().strftime("%d. %b %Y"), date, re.I)
date = re.sub("Morgen|Tomorrow", _tomorrow().strftime("%d. %b %Y"), date, re.I)
return datetime.datetime.strptime(date, "%d. %b %Y, %H:%M")
2020-04-30 12:00:21 +02:00
except ValueError:
PRETTY.warning(f"Could not parse date {date!r}")
return None
finally:
locale.setlocale(locale.LC_ALL, saved)
2020-04-22 12:44:41 +02:00
def _yesterday() -> datetime.date:
return datetime.date.today() - datetime.timedelta(days=1)
2020-04-30 12:00:21 +02:00
def _tomorrow() -> datetime.date:
return datetime.date.today() + datetime.timedelta(days=1)