annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/dateutil/utils.py @ 69:33d812a61356

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