1
# -*- coding: utf-8 -*-
2 84
"""
3
This module offers general convenience and utility functions for dealing with
4
datetimes.
5

6
.. versionadded:: 2.7.0
7
"""
8 84
from __future__ import unicode_literals
9

10 84
from datetime import datetime, time
11

12

13 84
def today(tzinfo=None):
14
    """
15
    Returns a :py:class:`datetime` representing the current day at midnight
16

17
    :param tzinfo:
18
        The time zone to attach (also used to determine the current day).
19

20
    :return:
21
        A :py:class:`datetime.datetime` object representing the current day
22
        at midnight.
23
    """
24

25 84
    dt = datetime.now(tzinfo)
26 84
    return datetime.combine(dt.date(), time(0, tzinfo=tzinfo))
27

28

29 84
def default_tzinfo(dt, tzinfo):
30
    """
31
    Sets the ``tzinfo`` parameter on naive datetimes only
32

33
    This is useful for example when you are provided a datetime that may have
34
    either an implicit or explicit time zone, such as when parsing a time zone
35
    string.
36

37
    .. doctest::
38

39
        >>> from dateutil.tz import tzoffset
40
        >>> from dateutil.parser import parse
41
        >>> from dateutil.utils import default_tzinfo
42
        >>> dflt_tz = tzoffset("EST", -18000)
43
        >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz))
44
        2014-01-01 12:30:00+00:00
45
        >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz))
46
        2014-01-01 12:30:00-05:00
47

48
    :param dt:
49
        The datetime on which to replace the time zone
50

51
    :param tzinfo:
52
        The :py:class:`datetime.tzinfo` subclass instance to assign to
53
        ``dt`` if (and only if) it is naive.
54

55
    :return:
56
        Returns an aware :py:class:`datetime.datetime`.
57
    """
58 84
    if dt.tzinfo is not None:
59 84
        return dt
60
    else:
61 84
        return dt.replace(tzinfo=tzinfo)
62

63

64 84
def within_delta(dt1, dt2, delta):
65
    """
66
    Useful for comparing two datetimes that may have a negligible difference
67
    to be considered equal.
68
    """
69 84
    delta = abs(delta)
70 84
    difference = dt1 - dt2
71 84
    return -delta <= difference <= delta

Read our documentation on viewing source code .

Loading