0

I would like to get the EST time with Python. I have the following code:

import datetime
from pytz import timezone
import time
now_EST = datetime.datetime.today().astimezone(timezone('EST'))
print(now_EST)

And the output is:

2022-03-29 09:52:55.130992-05:00

But when I google the EST time zone, I find out that the time right now is 10:52 am EST, which essentially is the right time.

Why does my code show the 1 hour earlier time compared to the correct one?

edn
  • 1,981
  • 3
  • 26
  • 56
  • EST is Eastern **Standard** Time. If you want the daylight saving timezone you need to ask for that instead. If you want the currently active timezone, you can do https://stackoverflow.com/questions/5946499/how-to-get-the-common-name-for-a-pytz-timezone-eg-est-edt-for-america-new-york – Pranav Hosangadi Mar 29 '22 at 15:17

2 Answers2

3

use a proper IANA time zone name to avoid ambiguities of the abbreviations.

from datetime import datetime
import pytz

print(datetime.now(pytz.timezone("America/New_York")))
# 2022-03-29 11:20:30.917144-04:00

If you happen to use Python 3.9 or higher, use the built-in zoneinfo module to set the time zone (pytz is deprecated):

from datetime import datetime
from zoneinfo import ZoneInfo

print(datetime.now(ZoneInfo("America/New_York")))
# 2022-03-29 11:20:30.917144-04:00
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • If I specifically say datetime.now(pytz.timezone("America/New_York")), do I always get the actual real time of New York throughout the year no matter daylight saving is active or not? – edn Mar 29 '22 at 15:20
  • 1
    @edn yes, exactly. – FObersteiner Mar 29 '22 at 15:21
2

Daylight Saving Time. Try "EST5EDT"

slass100
  • 66
  • 4
  • Thank you for your reply! Does EST5EDT always work then independent from daylight saving time changes? – edn Mar 29 '22 at 15:01
  • @edn see [eggert tz / northamerica](https://github.com/eggert/tz/blob/main/northamerica): EST5EDT is obsolete, it's just in the IANA tz database for backwards compatibility aka "historical reasons". – FObersteiner Mar 29 '22 at 15:26
  • @FObersteiner Thanks a lot clarifying that as well! Specifying the exact location as "America/New_York" is then the correct way to go! – edn Mar 29 '22 at 15:40