You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

43 lines
1.4 KiB

  1. #!/usr/bin/env python3
  2. import re
  3. from dateutil.relativedelta import relativedelta
  4. from datetime import date
  5. from _kosmorro.i18n.utils import _
  6. def parse_date(date_arg: str) -> date:
  7. if re.match(r"^\d{4}-\d{2}-\d{2}$", date_arg):
  8. try:
  9. return date.fromisoformat(date_arg)
  10. except ValueError as error:
  11. raise ValueError(
  12. _("The date {date} is not valid: {error}").format(
  13. date=date_arg, error=error.args[0]
  14. )
  15. ) from error
  16. elif re.match(r"^([+-])(([0-9]+)y)?[ ]?(([0-9]+)m)?[ ]?(([0-9]+)d)?$", date_arg):
  17. def get_offset(date_arg: str, signifier: str):
  18. if re.search(r"([0-9]+)" + signifier, date_arg):
  19. return abs(
  20. int(re.search(r"[+-]?([0-9]+)" + signifier, date_arg).group(0)[:-1])
  21. )
  22. return 0
  23. days = get_offset(date_arg, "d")
  24. months = get_offset(date_arg, "m")
  25. years = get_offset(date_arg, "y")
  26. if date_arg[0] == "+":
  27. return date.today() + relativedelta(days=days, months=months, years=years)
  28. return date.today() - relativedelta(days=days, months=months, years=years)
  29. else:
  30. error_msg = _(
  31. "The date {date} does not match the required YYYY-MM-DD format or the offset format."
  32. )
  33. raise ValueError(error_msg.format(date=date_arg))