Repository: sdispater/pendulum (python)

Issue:
deepcopy on DateTime produces incorrect offset in copy during dst transition
<!--
  Hi there! Thank you for discovering and submitting an issue.

  Before you submit this; let's make sure of a few things.
  Please make sure the following boxes are ticked if they are correct.
  If not, please try and fulfill these first.
-->

<!-- Checked checkbox should look like this: [x] -->
- [x] I am on the [latest](https://github.com/sdispater/pendulum/releases/latest) Pendulum version.
- [x] I have searched the [issues](https://github.com/sdispater/pendulum/issues) of this repo and believe that this is not a duplicate.

<!--
  Once those are done, if you're able to fill in the following list with your information,
  it'd be very helpful to whoever handles the issue.
-->

- **OS version and name**: MacOS 12.0.1 Monterey
- **Pendulum version**: 2.1.2
- **Python version**: 3.11.5

Issue also presents on python 3.10.1 and python 3.10.13

## Issue
<!-- Now feel free to write your issue, but please be descriptive! Thanks again 🙌 ❤️ -->

When passing a DateTime undergoing dst transition to standard deepcopy, the produced DateTime has an invalid offset.

## Reproduction

### Code

```python
import pendulum
from copy import deepcopy

d = pendulum.from_timestamp(1699174800.0, tz="US/Pacific")

print(f"Original: {d!r}")
print(d.isoformat())
print(d.timestamp())

d2 = deepcopy(d)
print(f"Copied: {d2!r}")
print(d2.isoformat())
print(d2.timestamp())
```

### Output

```
Original: DateTime(2023, 11, 5, 1, 0, 0, tzinfo=Timezone('US/Pacific'))
2023-11-05T01:00:00-08:00
1699174800.0
Copied: DateTime(2023, 11, 5, 1, 0, 0, tzinfo=Timezone('US/Pacific'))
2023-11-05T01:00:00-07:00
1699171200.0
```

## Workaround

An ugly hack can be used to work around the issue:

```python
# UGLY HACK
from pendulum.datetime import DateTime
DateTime.__deepcopy__ = lambda d, *args: d

# Script from above
import pendulum
from copy import deepcopy

d = pendulum.from_timestamp(1699174800.0, tz="US/Pacific")

print(f"Original: {d!r}")
print(d.isoformat())
print(d.timestamp())

d2 = deepcopy(d)
print(f"Copied: {d2!r}")
print(d2.isoformat())
print(d2.timestamp())
```

Result:
```
Original: DateTime(2023, 11, 5, 1, 0, 0, tzinfo=Timezone('US/Pacific'))
2023-11-05T01:00:00-08:00
1699174800.0
Copied: DateTime(2023, 11, 5, 1, 0, 0, tzinfo=Timezone('US/Pacific'))
2023-11-05T01:00:00-08:00
1699174800.0
```

## Relevance

Deepcopy on DateTimes occurs any time dataclass' module-level `asdict` is called on a dataclass object that contains DateTime objects, triggering this bug. `asdict` in turn is called by pydantic's json encoder function `pydantic_encoder`, which is how we found out about this in the first place.

Pull request:
Fix handling of the fold attribute when deep copying DateTime objects
Fixes #767

## Pull Request Check List

- [x] Added **tests** for changed code.
- [ ] Updated **documentation** for changed code.


Patch:
diff --git a/src/pendulum/__init__.py b/src/pendulum/__init__.py
index 43346e5..3863b76 100644
--- a/src/pendulum/__init__.py
+++ b/src/pendulum/__init__.py
@@ -50,7 +50,6 @@ FRIDAY = WeekDay.FRIDAY
 SATURDAY = WeekDay.SATURDAY
 SUNDAY = WeekDay.SUNDAY
 
-
 _TEST_NOW: DateTime | None = None
 _LOCALE = "en"
 _WEEK_STARTS_AT: WeekDay = WeekDay.MONDAY
diff --git a/src/pendulum/date.py b/src/pendulum/date.py
index 5e69ec0..e7b862c 100644
--- a/src/pendulum/date.py
+++ b/src/pendulum/date.py
@@ -74,9 +74,7 @@ class Date(FormattableMixin, date):
 
     @property
     def week_of_month(self) -> int:
-        first_day_of_month = self.replace(day=1)
-
-        return self.week_of_year - first_day_of_month.week_of_year + 1
+        return math.ceil((self.day + self.first_of("month").isoweekday() - 1) / 7)
 
     @property
     def age(self) -> int:
diff --git a/src/pendulum/datetime.py b/src/pendulum/datetime.py
index 6452f3b..5367d31 100644
--- a/src/pendulum/datetime.py
+++ b/src/pendulum/datetime.py
@@ -1357,17 +1357,32 @@ class DateTime(datetime.datetime, Date):
     def __reduce__(
         self,
     ) -> tuple[
-        type[Self], tuple[int, int, int, int, int, int, int, datetime.tzinfo | None]
+        type[Self],
+        tuple[int, int, int, int, int, int, int, datetime.tzinfo | None],
     ]:
         return self.__reduce_ex__(2)
 
     def __reduce_ex__(
         self, protocol: SupportsIndex
     ) -> tuple[
-        type[Self], tuple[int, int, int, int, int, int, int, datetime.tzinfo | None]
+        type[Self],
+        tuple[int, int, int, int, int, int, int, datetime.tzinfo | None],
     ]:
         return self.__class__, self._getstate(protocol)
 
+    def __deepcopy__(self, _: dict[int, Self]) -> Self:
+        return self.__class__(
+            self.year,
+            self.month,
+            self.day,
+            self.hour,
+            self.minute,
+            self.second,
+            self.microsecond,
+            tzinfo=self.tz,
+            fold=self.fold,
+        )
+
     def _cmp(self, other: datetime.datetime, **kwargs: Any) -> int:
         # Fix for pypy which compares using this method
         # which would lead to infinite recursion if we didn't override


Test patch:
diff --git a/tests/datetime/test_behavior.py b/tests/datetime/test_behavior.py
index e02323a..76de1d6 100644
--- a/tests/datetime/test_behavior.py
+++ b/tests/datetime/test_behavior.py
@@ -158,6 +158,14 @@ def test_deepcopy():
     assert dt == deepcopy(dt)
 
 
+def test_deepcopy_on_transition():
+    dt = pendulum.datetime(2023, 11, 5, 1, 0, 0, tz="US/Pacific")
+    clone = deepcopy(dt)
+
+    assert dt == clone
+    assert dt.offset == clone.offset
+
+
 def test_pickle_timezone():
     dt1 = pendulum.timezone("Europe/Amsterdam")
     s = pickle.dumps(dt1)
diff --git a/tests/datetime/test_getters.py b/tests/datetime/test_getters.py
index 1911cb1..8f4c1ae 100644
--- a/tests/datetime/test_getters.py
+++ b/tests/datetime/test_getters.py
@@ -195,6 +195,14 @@ def test_week_of_year_last_week():
     assert pendulum.datetime(2012, 12, 31).week_of_year == 1
 
 
+def test_week_of_month_edge_case():
+    assert pendulum.datetime(2020, 1, 1).week_of_month == 1
+    assert pendulum.datetime(2020, 1, 7).week_of_month == 2
+    assert pendulum.datetime(2020, 1, 14).week_of_month == 3
+    assert pendulum.datetime(2023, 1, 1).week_of_month == 1
+    assert pendulum.datetime(2023, 1, 31).week_of_month == 6
+
+
 def test_timezone():
     d = pendulum.datetime(2000, 1, 1, tz="America/Toronto")
     assert d.timezone.name == "America/Toronto"
@@ -247,3 +255,41 @@ def test_time():
     t = dt.time()
     assert isinstance(t, pendulum.Time)
     assert_time(t, 10, 40, 34, 123456)
+
+
+@pytest.mark.parametrize(
+    "date, expected",
+    [
+        (pendulum.Date(2000, 1, 1), 1),
+        (pendulum.Date(2000, 1, 3), 2),
+        (pendulum.Date(2019, 12, 29), 5),
+        (pendulum.Date(2019, 12, 30), 6),
+        (pendulum.Date(2019, 12, 31), 6),
+        (pendulum.Date(2020, 1, 7), 2),
+        (pendulum.Date(2020, 1, 14), 3),
+        (pendulum.Date(2021, 1, 1), 1),
+        (pendulum.Date(2021, 1, 2), 1),
+        (pendulum.Date(2021, 1, 9), 2),
+        (pendulum.Date(2021, 1, 10), 2),
+        (pendulum.Date(2021, 1, 11), 3),
+        (pendulum.Date(2021, 1, 15), 3),
+        (pendulum.Date(2021, 1, 16), 3),
+        (pendulum.Date(2021, 1, 17), 3),
+        (pendulum.Date(2021, 1, 23), 4),
+        (pendulum.Date(2021, 1, 31), 5),
+        (pendulum.Date(2021, 12, 19), 3),
+        (pendulum.Date(2021, 12, 25), 4),
+        (pendulum.Date(2021, 12, 26), 4),
+        (pendulum.Date(2021, 12, 29), 5),
+        (pendulum.Date(2021, 12, 30), 5),
+        (pendulum.Date(2021, 12, 31), 5),
+        (pendulum.Date(2022, 1, 1), 1),
+        (pendulum.Date(2022, 1, 3), 2),
+        (pendulum.Date(2022, 1, 10), 3),
+        (pendulum.Date(2023, 1, 1), 1),
+        (pendulum.Date(2023, 1, 2), 2),
+        (pendulum.Date(2029, 12, 31), 6),
+    ],
+)
+def test_week_of_month_negative(date, expected):
+    assert date.week_of_month == expected