pendulum icon indicating copy to clipboard operation
pendulum copied to clipboard

DateTime.replace incorrectly changes the time of a naive datetime

Open sushinoya opened this issue 1 year ago • 2 comments

  • [x] I am on the latest Pendulum version.
  • [x] I have searched the issues of this repo and believe that this is not a duplicate.
  • OS version and name: MacOS 13.2.1
  • Pendulum version: 2.1.2

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".

sushinoya avatar Mar 07 '23 03:03 sushinoya

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...

jklymak avatar Mar 08 '23 15:03 jklymak

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

sushinoya avatar Mar 28 '23 03:03 sushinoya