How do I get New York City time?

Viewed 17619

I travel frequently but live in NYC and am trying to display NYC time no matter where I am. How do I do that in Python? I have the following, which doesn't work, giving me the error:

 `'module' object is not callable` 

Also, I'm not sure if my method below will correctly update with daylight savings time or not:

import pytz
utc = pytz.utc
utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
eastern = pytz.timezone('US/Eastern')
loc_dt = utc_dt.astimezone(eastern)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt.strftime(fmt)
4 Answers

It's cleaner to write your import like this:

from datetime import datetime
import pytz
now = datetime.now(tz=pytz.timezone('US/Eastern'))

This allows re-use of datetime further down your code, without having to datetime.datetime every single time. Also avoids importing the entire datetime module unnecessarily.

Also note that according to IANA, 'US/Eastern' has been deprecated. Perhaps consider 'America/New_York'

Related