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.

71 lines
1.9 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. This module offers general convenience and utility functions for dealing with
  4. datetimes.
  5. .. versionadded:: 2.7.0
  6. """
  7. from __future__ import unicode_literals
  8. from datetime import datetime, time
  9. def today(tzinfo=None):
  10. """
  11. Returns a :py:class:`datetime` representing the current day at midnight
  12. :param tzinfo:
  13. The time zone to attach (also used to determine the current day).
  14. :return:
  15. A :py:class:`datetime.datetime` object representing the current day
  16. at midnight.
  17. """
  18. dt = datetime.now(tzinfo)
  19. return datetime.combine(dt.date(), time(0, tzinfo=tzinfo))
  20. def default_tzinfo(dt, tzinfo):
  21. """
  22. Sets the the ``tzinfo`` parameter on naive datetimes only
  23. This is useful for example when you are provided a datetime that may have
  24. either an implicit or explicit time zone, such as when parsing a time zone
  25. string.
  26. .. doctest::
  27. >>> from dateutil.tz import tzoffset
  28. >>> from dateutil.parser import parse
  29. >>> from dateutil.utils import default_tzinfo
  30. >>> dflt_tz = tzoffset("EST", -18000)
  31. >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz))
  32. 2014-01-01 12:30:00+00:00
  33. >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz))
  34. 2014-01-01 12:30:00-05:00
  35. :param dt:
  36. The datetime on which to replace the time zone
  37. :param tzinfo:
  38. The :py:class:`datetime.tzinfo` subclass instance to assign to
  39. ``dt`` if (and only if) it is naive.
  40. :return:
  41. Returns an aware :py:class:`datetime.datetime`.
  42. """
  43. if dt.tzinfo is not None:
  44. return dt
  45. else:
  46. return dt.replace(tzinfo=tzinfo)
  47. def within_delta(dt1, dt2, delta):
  48. """
  49. Useful for comparing two datetimes that may a negilible difference
  50. to be considered equal.
  51. """
  52. delta = abs(delta)
  53. difference = dt1 - dt2
  54. return -delta <= difference <= delta