我如何获得纽约市时间?

use*_*084 0 python

我经常旅行,但住在纽约,我正试图显示纽约时间,无论我在哪里.我怎么用Python做到这一点?我有以下,这不起作用,给我错误:

 `'module' object is not callable` 
Run Code Online (Sandbox Code Playgroud)

此外,我不确定下面的方法是否会在夏令时之间正确更新:

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)
Run Code Online (Sandbox Code Playgroud)

Isa*_*aac 8

像这样编写导入会更干净:

from datetime import datetime
import pytz
now = datetime.now(tz=pytz.timezone('US/Eastern'))
Run Code Online (Sandbox Code Playgroud)

这允许在代码中进一步重复使用日期时间,而不必每次都使用 datetime.datetime 。还避免不必要地导入整个日期时间模块。

另请注意,根据 IANA,“美国/东部”已被弃用。也许考虑“美国/纽约”


phi*_*hag 7

而不是datetime写,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)
Run Code Online (Sandbox Code Playgroud)

那是因为模块datetime包含一个类datetime.datetime.


gio*_*lla 5

您可以按以下方式datetime使用该now()方法获取特定时区中当前时间的对象:

import datetime, pytz
nyc_datetime = datetime.datetime.now(pytz.timezone('US/Eastern'))
Run Code Online (Sandbox Code Playgroud)