1
tz1 = pytz.timezone('UTC')
dt1 = tz1.localize(datetime(2020, 10, 25,0,38,43,454000))

tz2 = pytz.timezone('Europe/London')
dt2 = tz2.localize(datetime(2020, 10, 25,1,38,43,454000))


print(dt1)
print(dt2)
print(dt1==dt2)

It returns:

2020-10-25 00:38:43.454000+00:00
2020-10-25 01:38:43.454000+00:00
False
tz1 = pytz.timezone('UTC')
dt1 = tz1.localize(datetime(2020, 10, 25,0,38,43,454000))

tz2 = pytz.timezone('Europe/London')
dt2 = tz2.localize(datetime(2020, 10, 25,0,38,43,454000))


print(dt1)
print(dt2)
print(dt1==dt2)

returns:

2020-10-25 00:38:43.454000+00:00
2020-10-25 00:38:43.454000+01:00
False

How can I make dt1==dt2 return True while only adjusting dt2?

Note: 2020/10/25 is the day when DST ends in 2020.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
xzk
  • 827
  • 2
  • 18
  • 43

1 Answers1

-2

Let's talk about dt1 and dt2, which are datetime objects. dt1 is set to the UTC timezone, while dt2 is set to the Europe/London timezone. Keep in mind that the Europe/London timezone follows daylight saving time (DST), so dt2 is adjusted to consider the DST offset at that specific time.

Now, if you want dt1 and dt2 to be equal, you can modify dt2 to match the local time during the DST transition. You can do this using the is_dst parameter of the localize() method.

Here's an example of code snippet for the possible resolution:

import pytz
from datetime import datetime

# Set up time zones
tz1 = pytz.timezone('UTC')
tz2 = pytz.timezone('Europe/London')

# Define the datetime in UTC
dt1 = datetime(2020, 10, 25, 0, 38, 43, 454000, tz1)

# Convert the datetime to the London timezone
dt2 = dt1.astimezone(tz2)

# Check if the two datetimes are equal
print(dt1)
print(dt2)
print(dt1 == dt2)

Output should be:

2020-10-25 00:38:43.454000+00:00
2020-10-25 01:38:43.454000+01:00
True
  • Thanks for your answer. I tried your code snippet but still got False. ```dt2``` is equal to ```2020-10-25 00:38:43.454000+01:00``` which is different from ```dt1``` – xzk Mar 30 '23 at 06:00
  • I already edited the `code snippet`. Hope it works. This time, I got it and it prints `True`. – Innoeyvative Mar 30 '23 at 06:16
  • 1
    `datetime(2020, 10, 25, 0, 38, 43, 454000, tz1)` - that's **not** how you set a pytz timezone object. Use `localize`. Otherwise, you get the [weird timezone issue with pytz](https://stackoverflow.com/q/11473721/10197418). Although direct placement in the datetime constructor works with UTC, it's better not to do so to avoid the ambiguity. – FObersteiner Mar 30 '23 at 06:20