jpayne@69: # -*- coding: utf-8 -*- jpayne@69: """ jpayne@69: This module offers general convenience and utility functions for dealing with jpayne@69: datetimes. jpayne@69: jpayne@69: .. versionadded:: 2.7.0 jpayne@69: """ jpayne@69: from __future__ import unicode_literals jpayne@69: jpayne@69: from datetime import datetime, time jpayne@69: jpayne@69: jpayne@69: def today(tzinfo=None): jpayne@69: """ jpayne@69: Returns a :py:class:`datetime` representing the current day at midnight jpayne@69: jpayne@69: :param tzinfo: jpayne@69: The time zone to attach (also used to determine the current day). jpayne@69: jpayne@69: :return: jpayne@69: A :py:class:`datetime.datetime` object representing the current day jpayne@69: at midnight. jpayne@69: """ jpayne@69: jpayne@69: dt = datetime.now(tzinfo) jpayne@69: return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) jpayne@69: jpayne@69: jpayne@69: def default_tzinfo(dt, tzinfo): jpayne@69: """ jpayne@69: Sets the ``tzinfo`` parameter on naive datetimes only jpayne@69: jpayne@69: This is useful for example when you are provided a datetime that may have jpayne@69: either an implicit or explicit time zone, such as when parsing a time zone jpayne@69: string. jpayne@69: jpayne@69: .. doctest:: jpayne@69: jpayne@69: >>> from dateutil.tz import tzoffset jpayne@69: >>> from dateutil.parser import parse jpayne@69: >>> from dateutil.utils import default_tzinfo jpayne@69: >>> dflt_tz = tzoffset("EST", -18000) jpayne@69: >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) jpayne@69: 2014-01-01 12:30:00+00:00 jpayne@69: >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) jpayne@69: 2014-01-01 12:30:00-05:00 jpayne@69: jpayne@69: :param dt: jpayne@69: The datetime on which to replace the time zone jpayne@69: jpayne@69: :param tzinfo: jpayne@69: The :py:class:`datetime.tzinfo` subclass instance to assign to jpayne@69: ``dt`` if (and only if) it is naive. jpayne@69: jpayne@69: :return: jpayne@69: Returns an aware :py:class:`datetime.datetime`. jpayne@69: """ jpayne@69: if dt.tzinfo is not None: jpayne@69: return dt jpayne@69: else: jpayne@69: return dt.replace(tzinfo=tzinfo) jpayne@69: jpayne@69: jpayne@69: def within_delta(dt1, dt2, delta): jpayne@69: """ jpayne@69: Useful for comparing two datetimes that may have a negligible difference jpayne@69: to be considered equal. jpayne@69: """ jpayne@69: delta = abs(delta) jpayne@69: difference = dt1 - dt2 jpayne@69: return -delta <= difference <= delta