0

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.

Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16

2 Answers2

0

I think what you want to do is use tz.localize, your function would become:

from datetime import datetime
import pytz

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

With this function you get the right results.

NuLo
  • 1,298
  • 1
  • 11
  • 16
  • There it is, in datetime (not date) object: https://docs.python.org/3/library/datetime.html#datetime.datetime.replace dt = tz.localize(dt) just putting my own local timezone - it cant be specific (like that stores in tz_str) – Evgeny Mishkin Sep 03 '21 at 11:53
  • You're right about the datetime, sorry about that (I'll remove that part). But I think you are wrong about localize. I found [this question](https://stackoverflow.com/questions/1379740/pytz-localize-vs-datetime-replace) that can help clarify things. I've tested the code and it gives: `Europe/Kirov b: 2018-01-01 00:00:00+03:00 America/Panama c: 2018-01-01 00:00:00-05:00 ` which I think where the expected results – NuLo Sep 03 '21 at 12:06
0

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