shady
shady

Reputation: 63

pytz returns LMT timezone instead of GMT when pytz.timezone() passed to tzinfo

from datetime import datetime
from pytz import timezone
d1 = datetime.now(tz = timezone('Asia/Calcutta'))
d2 = datetime(2019,12,12,12,12,12,12)
zone = timezone('Asia/Calcutta')
d2 = zone.localize(d2)
d3 = datetime(2019,12,12,12,12,12,12,tzinfo = timezone('Asia/Calcutta'))
print(d1,d1.tzinfo.tzname)
print(d2,d2.tzinfo.tzname)
print(d3,d3.tzinfo.tzname)

This is the output i got

2021-07-03 14:00:03.135000+05:30 <bound method DstTzInfo.tzname of <DstTzInfo 'Asia/Calcutta' IST+5:30:00 STD>>
2019-12-12 12:12:12.000012+05:30 <bound method DstTzInfo.tzname of <DstTzInfo 'Asia/Calcutta' IST+5:30:00 STD>>
2019-12-12 12:12:12.000012+05:53 <bound method DstTzInfo.tzname of <DstTzInfo 'Asia/Calcutta' LMT+5:53:00 STD>>

Just look at the timezones ,as you can see from the output whenever i try to pass timezone with tzinfo as i did in the last d3 object it gives me LMT+5:53 instead of +5:30 , but the first two date objects work fine , help me out

Upvotes: 5

Views: 4495

Answers (2)

Raghuraman
Raghuraman

Reputation: 101

please refer to https://pythonhosted.org/pytz/ It is mentioned that

'Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.'

and

'The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.'

I am sorry, I couldn't understand the intention behind your code. From what I thought , perhaps this may be, what you wanted.

from datetime import datetime
import pytz

d1 = datetime.utcnow() # d1 is naive
d2 = datetime(2019,12,12,12,12,12,12) # d2 too
zone = pytz.timezone('Asia/Calcutta')  
d2 = zone.localize(d2) # d2 has become aware now
d3  = datetime(2019,12,12,12,12,12,12,tzinfo = pytz.utc)

print(d1)
print(d2,d2.tzinfo.tzname(d2))
print(d3,d3.tzinfo.tzname(d3))

The output is

2021-07-20 07:07:22.542644
2019-12-12 12:12:12.000012+05:30 IST
2019-12-12 12:12:12.000012+00:00 UTC

The same code using zoneinfo module (python 3.9) where there is no restriction for giving tzinfo in the constructor. (zoneinfo module)

from datetime import datetime
from zoneinfo import *

d1 = datetime.utcnow() 
d2 = datetime(2019,12,12,12,12,12,12,tzinfo= ZoneInfo('Asia/Calcutta'))
d3  = datetime(2019,12,12,12,12,12,12,tzinfo = ZoneInfo('utc'))
print(d1)
print(d2,d2.tzinfo.tzname(d2))
print(d3,d3.tzinfo.tzname(d3))

The output is

2021-07-20 07:13:52.749333
2019-12-12 12:12:12.000012+05:30 IST
2019-12-12 12:12:12.000012+00:00 UTC

Hope this is useful.

with best regards

Upvotes: 8

V Bota
V Bota

Reputation: 617

I agree with the response from "Raghuraman".

The work around that I used is:

    parsed = datetime.strptime(source, "%Y-%m-%d %H:%M:%S.%f")
    result = pytz.timezone('Asia/Calcutta').localize(parsed)

Upvotes: 2

Related Questions