1 """Various utilities for handling dates."""
2 from datetime import datetime, timedelta
3 from plomtask.exceptions import BadFormatException
5 DATE_FORMAT = '%Y-%m-%d'
8 def valid_date(date_str: str) -> str:
9 """Validate date against DATE_FORMAT or 'today'/'yesterday'/'tomorrow.
11 In any case, returns in DATE_FORMAT.
13 if date_str == 'today':
14 date_str = date_in_n_days(0)
15 elif date_str == 'yesterday':
16 date_str = date_in_n_days(-1)
17 elif date_str == 'tomorrow':
18 date_str = date_in_n_days(1)
20 dt = datetime.strptime(date_str, DATE_FORMAT)
21 except (ValueError, TypeError) as e:
22 msg = f'Given date of wrong format: {date_str}'
23 raise BadFormatException(msg) from e
24 return dt.strftime(DATE_FORMAT)
27 def date_in_n_days(n: int) -> str:
28 """Return in DATE_FORMAT date from today + n days."""
29 date = datetime.now() + timedelta(days=n)
30 return date.strftime(DATE_FORMAT)