annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/dateutil/utils.py @ 68:5028fdace37b

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