berkayln
berkayln

Reputation: 995

Converting local times to UTC for different countries

I would like to convert local times to UTC tine for different countries. I'm trying to do that with this way:

tz = pytz.timezone('Europe/Berlin')
x=tz.normalize(tz.localize(datetime.now())).astimezone(pytz.utc)

It gives me right result. But when I try to do that for Europe/Lisbon, I get wrong result. Can it be a problem or am I doing something wrong? There is no difference between two time zones but it gives me 3 hours difference as below.

enter image description here

Thanks in advance.

Upvotes: 0

Views: 1318

Answers (2)

Anand Gautam
Anand Gautam

Reputation: 2101

I am not sure why you get the wrong times. I tried this way and I get the right ones. It's just that I have frozen the current time to a variable and used it to check as a debug. Lisbon has the time as UTC - no difference P.S. I am in local time zone though, and hence you may see my time as different from yours but the difference seems to be right. Berlin is 1 hour ahead of UTC while Lisbon is same as UTC

import pytz
from datetime import datetime

tz = pytz.timezone('Europe/Berlin')
tb = tz.localize(datetime.now())
print(f"Berlin Time:   {tb}")
x=tz.normalize(tb).astimezone(pytz.utc)
print(f"Berin to UTC:   {x}")

tz2 = pytz.timezone('Europe/Lisbon')
tl = tz2.localize(datetime.now())
print(f"Lisbon Time:   {tl}")
y=tz2.normalize(tl).astimezone(pytz.utc)
print(f"Lisbon to UTC:   {tl}")

Here is the result:

Berlin Time:   2022-01-05 20:19:28.576504+01:00
Berin to UTC:   2022-01-05 19:19:28.576504+00:00
Lisbon Time:   2022-01-05 20:19:28.578506+00:00
Lisbon to UTC:   2022-01-05 20:19:28.578506+00:00

Process finished with exit code 0

Upvotes: 1

P S Solanki
P S Solanki

Reputation: 1123

This should work well for converting your local time to a timezone aware UTC datetime object

I'm guessing you might have issues with DST. The call to localize() requires you to specify if the timezone is serving DST or not. It defaults to False.

Other possibility is simply the fact that you're using your local times (considering you're not yourself in lisbon) and since you localize that time to lisbon timezone, of course it would result in incorrect time.

import pytz
import datetime


timezone = pytz.timezone('Europe/Lisbon')

original_time = datetime.datetime(2021, 10, 15, 13, 15)  # change this to sample datetime to test different values

local_timezone_datetime = timezone.localize(original_time, False)  # change False to True if DST is enabled on the timezone

converted_datetime = local_timezone_datetime.astimezone(pytz.utc)

print(converted_datetime)

Lemme know if you need a function to help you determine whether a timezone is serving DST.

Upvotes: 0

Related Questions