Python 我怎么去纽约时间?
我经常旅行,但住在纽约,无论身在何处,我都在努力展示纽约的时间。在Python中如何做到这一点?我有以下不起作用的错误:Python 我怎么去纽约时间?,python,Python,我经常旅行,但住在纽约,无论身在何处,我都在努力展示纽约的时间。在Python中如何做到这一点?我有以下不起作用的错误: `'module' object is not callable` 此外,我不确定下面的方法是否会正确地使用夏令时更新: import pytz utc = pytz.utc utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) eastern = pytz.timezone('US/Eastern') loc_dt
`'module' object is not callable`
此外,我不确定下面的方法是否会正确地使用夏令时更新:
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)
编写
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)
这是因为模块包含一个类。我将改为:
import datetime
import pytz
now = datetime.datetime.now(tz=pytz.timezone('US/Eastern'))
print("now time is: ", now)
current_hour = now.hour
current_minute = now.minute
current_second = now.second
current_weekday = now.weekday()
您可以使用
now()
方法以以下方式获取特定时区中当前时间的datetime
对象:
import datetime, pytz
nyc_datetime = datetime.datetime.now(pytz.timezone('US/Eastern'))
这样编写导入更简洁:
from datetime import datetime
import pytz
now = datetime.now(tz=pytz.timezone('US/Eastern'))
这允许在代码的更深处重复使用datetime,而不必每次都使用datetime.datetime。还可以避免不必要地导入整个datetime模块
另请注意,根据IANA,“美国/东部”已被弃用。也许考虑一下“美国/纽约克”< /P>