Reputation: 288
I'm trying to print the current time in EST, but my results are off by one hour (when compared to Google's "est local time" and "nyc local time"). I've tried using both pytz
and dateutil
:
import datetime
import dateutil.tz
import pytz
# Correct
print(datetime.datetime.now())
# Correct
print(datetime.datetime.now(dateutil.tz.UTC))
# Off by one hour
print(str(datetime.datetime.now(dateutil.tz.gettz("EST"))))
# Off by one hour
print(str(pytz.utc.localize(datetime.datetime.utcnow()).astimezone(pytz.timezone("EST"))))
I've tried to research the correct way to do this, and the above is what I've found, yet the result is off (e.g. it shows 10 am EST when Google says it's 11 am). My local time is configured correctly. Am I missing something?
I'm using:
Upvotes: 0
Views: 2213
Reputation: 241808
Your time is off by an hour because daylight saving time is in effect at this time, and that is not represented when you specified EST
.
As mentioned in the question's comments - you should use a specific locality-based time zone name, such as America/New_York
instead of EST
.
The reason EST
works in both pytz and dateutil is that it is defined as an IANA time zone name:
From: https://github.com/eggert/tz/blob/2020a/northamerica#L188-L206
We generate the files specified below to guard against old files with obsolete information being left in the time zone binary directory. We limit the list to names that have appeared in previous versions of this time zone package...
# Zone NAME STDOFF RULES FORMAT [UNTIL] Zone EST -5:00 - EST Zone MST -7:00 - MST Zone HST -10:00 - HST Zone EST5EDT -5:00 US E%sT Zone CST6CDT -6:00 US C%sT Zone MST7MDT -7:00 US M%sT Zone PST8PDT -8:00 US P%sT
As you can see, EST
, MST
, and HST
are defined with fixed offsets. They do not observe any DST rules. There are no similar entries for PST
or CST
, nor for daylight variants like EDT
.
The zones with names like EST5EDT
are backwards compatible with older POSIX-style time zones, but only these 4 are defined.
Generally speaking, you should not use any of these zones. They are there for the guard only.
Upvotes: 3