Search code examples
pythondatetimepytz

Should I make datetime.now() timezone aware before converting to EST?


I have to do a bunch of time calculations on EST terms, is the 2nd of the two print statements the appropriate way to ensure that datetime.now() will return the appropriate TZ aware EST time from anywhere in the world? I assume the reason they are both returning the same values now is because my local time is EST. My logic is to make it TZ aware in UTC then convert to EST so I'm never relying on "local" time.

from datetime import datetime
from pytz import timezone

EST = timezone('America/New_York')

print(datetime.now(EST))
print(datetime.now(timezone('UTC')).astimezone(EST))

gives:

2017-11-22 16:58:55.236498-05:00
2017-11-22 16:58:55.237080-05:00

Solution

  • These will print the same time wherever you are. I'm not in EST, and they both give your local time. Local time comes from the default arguments:

    print(datetime.now())
    

    Your first line specifies that you want the time in EST. The second specifies UTC, but converts that to EST.

    Does that clear up the functioning for you?