Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pendulum/helpers.py: 63%
109 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-30 06:11 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-30 06:11 +0000
1from __future__ import annotations
3import os
4import struct
6from datetime import date
7from datetime import datetime
8from datetime import timedelta
9from math import copysign
10from typing import TYPE_CHECKING
11from typing import TypeVar
12from typing import overload
14import pendulum
16from pendulum.constants import DAYS_PER_MONTHS
17from pendulum.day import WeekDay
18from pendulum.formatting.difference_formatter import DifferenceFormatter
19from pendulum.locales.locale import Locale
22if TYPE_CHECKING:
23 # Prevent import cycles
24 from pendulum.duration import Duration
26with_extensions = os.getenv("PENDULUM_EXTENSIONS", "1") == "1"
28_DT = TypeVar("_DT", bound=datetime)
29_D = TypeVar("_D", bound=date)
31try:
32 if not with_extensions or struct.calcsize("P") == 4:
33 raise ImportError()
35 from _pendulum import PreciseDiff
36 from _pendulum import days_in_year
37 from _pendulum import is_leap
38 from _pendulum import is_long_year
39 from _pendulum import local_time
40 from _pendulum import precise_diff
41 from _pendulum import week_day
42except ImportError:
43 from pendulum._helpers import PreciseDiff # type: ignore[assignment]
44 from pendulum._helpers import days_in_year
45 from pendulum._helpers import is_leap
46 from pendulum._helpers import is_long_year
47 from pendulum._helpers import local_time
48 from pendulum._helpers import precise_diff # type: ignore[assignment]
49 from pendulum._helpers import week_day
51difference_formatter = DifferenceFormatter()
54@overload
55def add_duration(
56 dt: _DT,
57 years: int = 0,
58 months: int = 0,
59 weeks: int = 0,
60 days: int = 0,
61 hours: int = 0,
62 minutes: int = 0,
63 seconds: float = 0,
64 microseconds: int = 0,
65) -> _DT:
66 ...
69@overload
70def add_duration(
71 dt: _D,
72 years: int = 0,
73 months: int = 0,
74 weeks: int = 0,
75 days: int = 0,
76) -> _D:
77 pass
80def add_duration(
81 dt: date | datetime,
82 years: int = 0,
83 months: int = 0,
84 weeks: int = 0,
85 days: int = 0,
86 hours: int = 0,
87 minutes: int = 0,
88 seconds: float = 0,
89 microseconds: int = 0,
90) -> date | datetime:
91 """
92 Adds a duration to a date/datetime instance.
93 """
94 days += weeks * 7
96 if (
97 isinstance(dt, date)
98 and not isinstance(dt, datetime)
99 and any([hours, minutes, seconds, microseconds])
100 ):
101 raise RuntimeError("Time elements cannot be added to a date instance.")
103 # Normalizing
104 if abs(microseconds) > 999999:
105 s = _sign(microseconds)
106 div, mod = divmod(microseconds * s, 1000000)
107 microseconds = mod * s
108 seconds += div * s
110 if abs(seconds) > 59:
111 s = _sign(seconds)
112 div, mod = divmod(seconds * s, 60) # type: ignore[assignment]
113 seconds = mod * s
114 minutes += div * s
116 if abs(minutes) > 59:
117 s = _sign(minutes)
118 div, mod = divmod(minutes * s, 60)
119 minutes = mod * s
120 hours += div * s
122 if abs(hours) > 23:
123 s = _sign(hours)
124 div, mod = divmod(hours * s, 24)
125 hours = mod * s
126 days += div * s
128 if abs(months) > 11:
129 s = _sign(months)
130 div, mod = divmod(months * s, 12)
131 months = mod * s
132 years += div * s
134 year = dt.year + years
135 month = dt.month
137 if months:
138 month += months
139 if month > 12:
140 year += 1
141 month -= 12
142 elif month < 1:
143 year -= 1
144 month += 12
146 day = min(DAYS_PER_MONTHS[int(is_leap(year))][month], dt.day)
148 dt = dt.replace(year=year, month=month, day=day)
150 return dt + timedelta(
151 days=days,
152 hours=hours,
153 minutes=minutes,
154 seconds=seconds,
155 microseconds=microseconds,
156 )
159def format_diff(
160 diff: Duration,
161 is_now: bool = True,
162 absolute: bool = False,
163 locale: str | None = None,
164) -> str:
165 if locale is None:
166 locale = get_locale()
168 return difference_formatter.format(diff, is_now, absolute, locale)
171def _sign(x: float) -> int:
172 return int(copysign(1, x))
175# Global helpers
178def locale(name: str) -> Locale:
179 return Locale.load(name)
182def set_locale(name: str) -> None:
183 locale(name)
185 pendulum._LOCALE = name
188def get_locale() -> str:
189 return pendulum._LOCALE
192def week_starts_at(wday: WeekDay) -> None:
193 if wday < WeekDay.MONDAY or wday > WeekDay.SUNDAY:
194 raise ValueError("Invalid day of week")
196 pendulum._WEEK_STARTS_AT = wday
199def week_ends_at(wday: WeekDay) -> None:
200 if wday < WeekDay.MONDAY or wday > WeekDay.SUNDAY:
201 raise ValueError("Invalid day of week")
203 pendulum._WEEK_ENDS_AT = wday
206__all__ = [
207 "PreciseDiff",
208 "days_in_year",
209 "is_leap",
210 "is_long_year",
211 "local_time",
212 "precise_diff",
213 "week_day",
214 "add_duration",
215 "format_diff",
216 "locale",
217 "set_locale",
218 "get_locale",
219 "week_starts_at",
220 "week_ends_at",
221]