humanize_datetime.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. Helper functions that convert strftime formats into more readable representations.
  3. """
  4. from rest_framework import ISO_8601
  5. def datetime_formats(formats):
  6. format = ', '.join(formats).replace(
  7. ISO_8601,
  8. 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
  9. )
  10. return humanize_strptime(format)
  11. def date_formats(formats):
  12. format = ', '.join(formats).replace(ISO_8601, 'YYYY-MM-DD')
  13. return humanize_strptime(format)
  14. def time_formats(formats):
  15. format = ', '.join(formats).replace(ISO_8601, 'hh:mm[:ss[.uuuuuu]]')
  16. return humanize_strptime(format)
  17. def humanize_strptime(format_string):
  18. # Note that we're missing some of the locale specific mappings that
  19. # don't really make sense.
  20. mapping = {
  21. "%Y": "YYYY",
  22. "%y": "YY",
  23. "%m": "MM",
  24. "%b": "[Jan-Dec]",
  25. "%B": "[January-December]",
  26. "%d": "DD",
  27. "%H": "hh",
  28. "%I": "hh", # Requires '%p' to differentiate from '%H'.
  29. "%M": "mm",
  30. "%S": "ss",
  31. "%f": "uuuuuu",
  32. "%a": "[Mon-Sun]",
  33. "%A": "[Monday-Sunday]",
  34. "%p": "[AM|PM]",
  35. "%z": "[+HHMM|-HHMM]"
  36. }
  37. for key, val in mapping.items():
  38. format_string = format_string.replace(key, val)
  39. return format_string