sdispater / pendulum

Python datetimes made easy
https://pendulum.eustace.io
MIT License
6.18k stars 381 forks source link

DateTime.replace incorrectly changes the time of a naive datetime #697

Open sushinoya opened 1 year ago

sushinoya commented 1 year ago

Issue

When replacing the timezone of a naive DateTime, the time component changes in this particular case -

from pendulum import DateTime, timezone

us_timezone = timezone("America/New_York")

naive_datetime = DateTime(2023, 3, 12, 2, 30)
tz_aware_datetime = naive_datetime.replace(tzinfo=us_timezone)

print(tz_aware_datetime)
>>> 2023-03-12T01:30:00-05:00  # <-- The time changed from 2.30 to 1.30

If we do the same using datetime and pytz, we get 1.30 as we expect -

from datetime import datetime
from pytz import timezone

us_timezone = timezone("America/New_York")

naive_datetime = datetime(2023, 3, 12, 2, 30)
tz_aware_datetime = naive_datetime.replace(tzinfo=us_timezone)

print(tz_aware_datetime)
>>> 2023-03-12 02:30:00-04:56 # <-- The time did not change

Although an edge case, this is quite critical because I believe that .replace should ideally not be altering any other fields of the DateTime except the one it's "replacing".

jklymak commented 1 year ago

Although an edge case, this is quite critical because I believe that .replace should ideally not be altering any other fields of the DateTime except the one it's "replacing".

This time doesn't exist because it's skipped during the switch from EST to EDT, so it's a little more than an edge case. I think one could argue that pendulum should error here, but...

sushinoya commented 1 year ago

@sdispater Do you have an opinion on the matter? Potentially erroring might also be better than silently shifting to the next valid time.