Printing Datetime As Pytz.timezone("etc/gmt-5") Yields Incorrect Result
Solution 1:
You are using pytz
, not just Python's datetime
.
Like dateutil, pytz uses the Olson tz database.
The Olson tz database defines Etc/GMT+N
timezones which conform with the POSIX style:
those zone names beginning with "Etc/GMT" have their sign reversed from the standard ISO 8601 convention. In the "Etc" area, zones west of GMT have a positive sign and those east have a negative sign in their name (e.g "Etc/GMT-14" is 14 hours ahead of GMT.)
So, to convert UTC to a timezone with offset -5 you could use Etc/GMT+5
:
import datetime as DT
import pytz
naive = DT.datetime(2019, 3, 7, 7, 45)
utc = pytz.utc
gmt5 = pytz.timezone('Etc/GMT+5')
print(utc.localize(naive).astimezone(gmt5))
# 2019-03-07 02:45:00-05:00
Solution 2:
Apparently, in posix style systems, you have to use the inverse of the timezone offset. That means if you want to get -5
, you have to use GMT+5
.
d3 = d2.astimezone(pytz.timezone('Etc/GMT+5'))
prints
UTC-5:2019-03-07 02:45:00-05:00
Otherwise, you have to pass the posix_offset
as true. This is in dateutil documentation;
There is one notable exception, which is that POSIX-style time zones use an inverted offset format, so normally GMT+3 would be parsed as an offset 3 hours behind GMT. The tzstr time zone object will parse this as an offset 3 hours ahead of GMT. If you would like to maintain the POSIX behavior, pass a True value to posix_offset.
https://dateutil.readthedocs.io/en/stable/tz.html#dateutil.tz.tzstr
Post a Comment for "Printing Datetime As Pytz.timezone("etc/gmt-5") Yields Incorrect Result"