summaryrefslogtreecommitdiffstats
path: root/pendulum/helpers.py
blob: 13b7f221c6c27f34fd144f2a387b2e0a20688840 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
from __future__ import annotations

import os
import struct

from datetime import date
from datetime import datetime
from datetime import timedelta
from math import copysign
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import overload

import pendulum

from pendulum.constants import DAYS_PER_MONTHS
from pendulum.formatting.difference_formatter import DifferenceFormatter
from pendulum.locales.locale import Locale

if TYPE_CHECKING:
    # Prevent import cycles
    from pendulum.duration import Duration

with_extensions = os.getenv("PENDULUM_EXTENSIONS", "1") == "1"

_DT = TypeVar("_DT", bound=datetime)
_D = TypeVar("_D", bound=date)

try:
    # nopycln: file # noqa: E800
    if not with_extensions or struct.calcsize("P") == 4:
        raise ImportError()

    from pendulum._extensions._helpers import PreciseDiff
    from pendulum._extensions._helpers import days_in_year
    from pendulum._extensions._helpers import is_leap
    from pendulum._extensions._helpers import is_long_year
    from pendulum._extensions._helpers import local_time
    from pendulum._extensions._helpers import precise_diff
    from pendulum._extensions._helpers import timestamp
    from pendulum._extensions._helpers import week_day
except ImportError:
    from pendulum._extensions.helpers import PreciseDiff  # type: ignore[misc]
    from pendulum._extensions.helpers import days_in_year
    from pendulum._extensions.helpers import is_leap
    from pendulum._extensions.helpers import is_long_year
    from pendulum._extensions.helpers import local_time
    from pendulum._extensions.helpers import precise_diff  # type: ignore[misc]
    from pendulum._extensions.helpers import timestamp
    from pendulum._extensions.helpers import week_day

difference_formatter = DifferenceFormatter()


@overload
def add_duration(
    dt: datetime,
    years: int = 0,
    months: int = 0,
    weeks: int = 0,
    days: int = 0,
    hours: int = 0,
    minutes: int = 0,
    seconds: float = 0,
    microseconds: int = 0,
) -> datetime:
    ...


@overload
def add_duration(
    dt: date,
    years: int = 0,
    months: int = 0,
    weeks: int = 0,
    days: int = 0,
) -> date:
    pass


def add_duration(
    dt: date | datetime,
    years: int = 0,
    months: int = 0,
    weeks: int = 0,
    days: int = 0,
    hours: int = 0,
    minutes: int = 0,
    seconds: float = 0,
    microseconds: int = 0,
) -> date | datetime:
    """
    Adds a duration to a date/datetime instance.
    """
    days += weeks * 7

    if (
        isinstance(dt, date)
        and not isinstance(dt, datetime)
        and any([hours, minutes, seconds, microseconds])
    ):
        raise RuntimeError("Time elements cannot be added to a date instance.")

    # Normalizing
    if abs(microseconds) > 999999:
        s = _sign(microseconds)
        div, mod = divmod(microseconds * s, 1000000)
        microseconds = mod * s
        seconds += div * s

    if abs(seconds) > 59:
        s = _sign(seconds)
        div, mod = divmod(seconds * s, 60)  # type: ignore[assignment]
        seconds = mod * s
        minutes += div * s

    if abs(minutes) > 59:
        s = _sign(minutes)
        div, mod = divmod(minutes * s, 60)
        minutes = mod * s
        hours += div * s

    if abs(hours) > 23:
        s = _sign(hours)
        div, mod = divmod(hours * s, 24)
        hours = mod * s
        days += div * s

    if abs(months) > 11:
        s = _sign(months)
        div, mod = divmod(months * s, 12)
        months = mod * s
        years += div * s

    year = dt.year + years
    month = dt.month

    if months:
        month += months
        if month > 12:
            year += 1
            month -= 12
        elif month < 1:
            year -= 1
            month += 12

    day = min(DAYS_PER_MONTHS[int(is_leap(year))][month], dt.day)

    dt = dt.replace(year=year, month=month, day=day)

    return dt + timedelta(
        days=days,
        hours=hours,
        minutes=minutes,
        seconds=seconds,
        microseconds=microseconds,
    )


def format_diff(
    diff: Duration,
    is_now: bool = True,
    absolute: bool = False,
    locale: str | None = None,
) -> str:
    if locale is None:
        locale = get_locale()

    return difference_formatter.format(diff, is_now, absolute, locale)


def _sign(x: float) -> int:
    return int(copysign(1, x))


# Global helpers


def locale(name: str) -> Locale:
    return Locale.load(name)


def set_locale(name: str) -> None:
    locale(name)

    pendulum._LOCALE = name


def get_locale() -> str:
    return pendulum._LOCALE


def week_starts_at(wday: int) -> None:
    if wday < pendulum.SUNDAY or wday > pendulum.SATURDAY:
        raise ValueError("Invalid week day as start of week.")

    pendulum._WEEK_STARTS_AT = wday


def week_ends_at(wday: int) -> None:
    if wday < pendulum.SUNDAY or wday > pendulum.SATURDAY:
        raise ValueError("Invalid week day as start of week.")

    pendulum._WEEK_ENDS_AT = wday


__all__ = [
    "PreciseDiff",
    "days_in_year",
    "is_leap",
    "is_long_year",
    "local_time",
    "precise_diff",
    "timestamp",
    "week_day",
    "add_duration",
    "format_diff",
    "locale",
    "set_locale",
    "get_locale",
    "week_starts_at",
    "week_ends_at",
]