Skip to content
Advertisement

adding tzinfo for naive datetime cause strange offset?

I’m just trying to add tzinfo for my datetime object (with no specific time). I have date in str format, and timezone in str format. I created this function:

from datetime import datetime
import pytz

def _converttime(dt_str, tz_str):
    dt = datetime.fromisoformat(dt_str)
    tz = pytz.timezone(tz_str)
    dt = dt.replace(tzinfo=tz)
    return dt

all looks fine when I am using tzinfo like: “Etc/GMT-6”:

a = _converttime("2018-01-01", "Etc/GMT-6")
        print(f'a: {a}')
>>a: 2018-01-01 00:00:00+06:00

but look at this:

 b = _converttime("2018-01-01", "Europe/Kirov")
        print(f'b: {b}')
>>b: 2018-01-01 00:00:00+03:19

c = _converttime("2018-01-01", "America/Panama")
        print(f'c: {c}')
>>c: 2018-01-01 00:00:00-05:18

Why do I get such a strange values like 03:19, 05:18 when it should be 03:00, -05:00? It cause problems lately.

Advertisement

Answer

Ok, i dont know whats wrong with this, but i found solution using django make_aware:

from django.utils.timezone import make_aware

def _converttime2(dt_str, tz_str):
    dt = datetime.fromisoformat(dt_str)
    tz = pytz.timezone(tz_str)
    dt = make_aware(dt, tz)
    return dt
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement