timeutils.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """
  2. celery.utils.timeutils
  3. ======================
  4. This module contains various utilties relating to time and date.
  5. """
  6. from __future__ import absolute_import
  7. import math
  8. from datetime import datetime, timedelta
  9. from dateutil.parser import parse as parse_iso8601
  10. __all__ = ["maybe_timedelta", "timedelta_seconds", "delta_resolution",
  11. "remaining", "rate", "weekday", "humanize_seconds",
  12. "maybe_iso8601"]
  13. DAYNAMES = "sun", "mon", "tue", "wed", "thu", "fri", "sat"
  14. WEEKDAYS = dict((name, dow) for name, dow in zip(DAYNAMES, range(7)))
  15. RATE_MODIFIER_MAP = {"s": lambda n: n,
  16. "m": lambda n: n / 60.0,
  17. "h": lambda n: n / 60.0 / 60.0}
  18. HAVE_TIMEDELTA_TOTAL_SECONDS = hasattr(timedelta, "total_seconds")
  19. TIME_UNITS = (("day", 60 * 60 * 24, lambda n: int(math.ceil(n))),
  20. ("hour", 60 * 60, lambda n: int(math.ceil(n))),
  21. ("minute", 60, lambda n: int(math.ceil(n))),
  22. ("second", 1, lambda n: "%.2f" % n))
  23. def maybe_timedelta(delta):
  24. """Coerces integer to timedelta if `delta` is an integer."""
  25. if isinstance(delta, (int, float)):
  26. return timedelta(seconds=delta)
  27. return delta
  28. if HAVE_TIMEDELTA_TOTAL_SECONDS: # pragma: no cover
  29. def timedelta_seconds(delta):
  30. """Convert :class:`datetime.timedelta` to seconds.
  31. Doesn't account for negative values.
  32. """
  33. return max(delta.total_seconds(), 0)
  34. else: # pragma: no cover
  35. def timedelta_seconds(delta): # noqa
  36. """Convert :class:`datetime.timedelta` to seconds.
  37. Doesn't account for negative values.
  38. """
  39. if delta.days < 0:
  40. return 0
  41. return delta.days * 86400 + delta.seconds + (delta.microseconds / 10e5)
  42. def delta_resolution(dt, delta):
  43. """Round a datetime to the resolution of a timedelta.
  44. If the timedelta is in days, the datetime will be rounded
  45. to the nearest days, if the timedelta is in hours the datetime
  46. will be rounded to the nearest hour, and so on until seconds
  47. which will just return the original datetime.
  48. """
  49. delta = timedelta_seconds(delta)
  50. resolutions = ((3, lambda x: x / 86400),
  51. (4, lambda x: x / 3600),
  52. (5, lambda x: x / 60))
  53. args = dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second
  54. for res, predicate in resolutions:
  55. if predicate(delta) >= 1.0:
  56. return datetime(*args[:res])
  57. return dt
  58. def remaining(start, ends_in, now=None, relative=True):
  59. """Calculate the remaining time for a start date and a timedelta.
  60. e.g. "how many seconds left for 30 seconds after start?"
  61. :param start: Start :class:`~datetime.datetime`.
  62. :param ends_in: The end delta as a :class:`~datetime.timedelta`.
  63. :keyword relative: If set to :const:`False`, the end time will be
  64. calculated using :func:`delta_resolution` (i.e. rounded to the
  65. resolution of `ends_in`).
  66. :keyword now: Function returning the current time and date,
  67. defaults to :func:`datetime.now`.
  68. """
  69. now = now or datetime.now()
  70. end_date = start + ends_in
  71. if not relative:
  72. end_date = delta_resolution(end_date, ends_in)
  73. return end_date - now
  74. def rate(rate):
  75. """Parses rate strings, such as `"100/m"` or `"2/h"`
  76. and converts them to seconds."""
  77. if rate:
  78. if isinstance(rate, basestring):
  79. ops, _, modifier = rate.partition("/")
  80. return RATE_MODIFIER_MAP[modifier or "s"](int(ops)) or 0
  81. return rate or 0
  82. return 0
  83. def weekday(name):
  84. """Return the position of a weekday (0 - 7, where 0 is Sunday).
  85. Example::
  86. >>> weekday("sunday"), weekday("sun"), weekday("mon")
  87. (0, 0, 1)
  88. """
  89. abbreviation = name[0:3].lower()
  90. try:
  91. return WEEKDAYS[abbreviation]
  92. except KeyError:
  93. # Show original day name in exception, instead of abbr.
  94. raise KeyError(name)
  95. def humanize_seconds(secs, prefix=""):
  96. """Show seconds in human form, e.g. 60 is "1 minute", 7200 is "2
  97. hours"."""
  98. for unit, divider, formatter in TIME_UNITS:
  99. if secs >= divider:
  100. w = secs / divider
  101. punit = w > 1 and (unit + "s") or unit
  102. return "%s%s %s" % (prefix, formatter(w), punit)
  103. return "now"
  104. def maybe_iso8601(dt):
  105. """`Either datetime | str -> datetime or None -> None`"""
  106. if not dt:
  107. return
  108. if isinstance(dt, datetime):
  109. return dt
  110. return parse_iso8601(dt)