Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get New York City time?

Tags:

python

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)
like image 408
user_78361084 Avatar asked Aug 08 '12 21:08

user_78361084


2 Answers

Instead of datetime, write datetime.datetime:

import datetime
import pytz

utc = pytz.utc
utc_dt = datetime.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)

That's because the module datetime contains a class datetime.datetime.

like image 163
phihag Avatar answered Oct 01 '22 18:10

phihag


You can get a datetime object of the current time in a specific timezone using the now() method in the following fashion:

import datetime, pytz
nyc_datetime = datetime.datetime.now(pytz.timezone('US/Eastern'))
like image 35
giopromolla Avatar answered Oct 01 '22 19:10

giopromolla