Python 在不同的时区显示时间

Python 在不同的时区显示时间,python,time,timezone,Python,Time,Timezone,是否有一种优雅的方式来显示另一时区的当前时间 我想要一些具有以下总体精神的东西: cur = <Get the current time, perhaps datetime.datetime.now()> print("Local time {}".format(cur)) print("Pacific time {}".format(<something like cur.tz('PST')>)) print("Israeli time {}".format(<

是否有一种优雅的方式来显示另一时区的当前时间

我想要一些具有以下总体精神的东西:

cur = <Get the current time, perhaps datetime.datetime.now()>
print("Local time   {}".format(cur))
print("Pacific time {}".format(<something like cur.tz('PST')>))
print("Israeli time {}".format(<something like cur.tz('IST')>))
cur=
打印(“本地时间{}”。格式(cur))
打印(“太平洋时间{}”.format())
打印(“以色列时间{}”.format())
您可以使用该库:

你可以查一下


或者尝试使用。在这里,您可以找到一个带有一些使用示例的安装指南。

通过C库的时区设置,一种方法是

>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
更简单的方法是:

from datetime import datetime
from pytz import timezone    

south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')

这是我的实现:

from datetime import datetime
from pytz import timezone

def local_time(zone='Asia/Jerusalem'):
    other_zone = timezone(zone)
    other_zone_time = datetime.now(other_zone)
    return other_zone_time.strftime('%T')

我一直都需要时间信息,所以我的服务器上有一个整洁的.py脚本,它让我只需选择和取消选择我想按东->西的顺序显示的时区

它是这样打印的:

Australia/Sydney    :   2016-02-09 03:52:29 AEDT+1100
Asia/Singapore      :   2016-02-09 00:52:29 SGT+0800
Asia/Hong_Kong      :   2016-02-09 00:52:29 HKT+0800
EET                 :   2016-02-08 18:52:29 EET+0200
CET                 :   2016-02-08 17:52:29 CET+0100     <- you are HERE
UTC                 :   2016-02-08 16:52:29 UTC+0000
Europe/London       :   2016-02-08 16:52:29 GMT+0000
America/New_York    :   2016-02-08 11:52:29 EST-0500
America/Los_Angeles :   2016-02-08 08:52:29 PST-0800

此脚本使用了
pytz
datetime
模块,其结构符合要求:

#!/usr/bin/env python3

import pytz
from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc)

PST = pytz.timezone('US/Pacific')
IST = pytz.timezone('Asia/Jerusalem')

print("UTC time     {}".format(utc_dt.isoformat()))
print("Local time   {}".format(utc_dt.astimezone().isoformat()))
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Israeli time {}".format(utc_dt.astimezone(IST).isoformat()))
它的输出如下:

$ ./timezones.py 
UTC time     2019-02-23T01:09:51.452247+00:00
Local time   2019-02-23T14:09:51.452247+13:00
Pacific time 2019-02-22T17:09:51.452247-08:00
Israeli time 2019-02-23T03:09:51.452247+02:00

问题的最短答案如下:

from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
这将打印:

2019-06-20 12:48:56.862291+05:30


可以通过从
datetime
pytx
导入模块
datetime
来指定时区

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/Kolkata')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

Python 3.9:从标准库使用:

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

# Israel and US/Pacific time:
now_Israel = datetime.now(ZoneInfo('Israel'))
now_Pacific = datetime.now(ZoneInfo('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00

# for reference, local time and UTC:
now_UTC = datetime.now(tz=timezone.utc)
now_local = datetime.now().astimezone()
print(f"Local time   {now_local.isoformat(timespec='seconds')}")
print(f"UTC          {now_UTC.isoformat(timespec='seconds')}")
# Local time   2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin
# UTC          2021-03-26T15:09:18+00:00
注意:有一个用于
pytz

较旧版本的Python 3:您可以通过模块使用
zoneinfo
,也可以使用。dateutil的
tz.gettz
遵循与
zoneinfo.zoneinfo
相同的语义:

from dateutil.tz import gettz

now_Israel = datetime.now(gettz('Israel'))
now_Pacific = datetime.now(gettz('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00

最后,我在代码中大量使用了
pandas
,如果不需要的话,我不喜欢导入额外的库,因此我使用了一个简单而干净的解决方案:

import pandas as pd

t = pd.Timestamp.now('UTC') #pull UTC time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_UTC_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format

t = pd.Timestamp.now(tz='US/Eastern') #pull Eastern (EDT or EST, as current) time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_EAST_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format

print(f"The current UTC time is: {now_UTC_rounded} (rounded to the nearest 10 min)")
print(f"The current US/Eastern time is: {now_EAST_rounded} (rounded to the nearest 10 min)")
产出:

The current UTC time is: 1800 (rounded to the nearest 10 min)
The current US/Eastern time is: 1400 (rounded to the nearest 10 min)
(实际东部时间为14:03) 舍入特性很好,因为如果你试图在某个特定的时间触发某个事件,比如在某个小时,你可以在任何一方错过4分钟,仍然可以得到一个匹配


只是炫耀一下功能——显然,如果你不想的话,你不需要使用回合

正副本:谢谢。当我搜索主题时没有找到它。根据文档,此主题的可能副本仅适用于Unix。我不确定这是否有什么不同。我需要一个解决方案,它不使用pytz,只需要在Linux系统上运行,所以这是完美的。这个解决方案在AWS Lambda中完美地工作,没有pytz。非常感谢。和上一次没什么不同。只有功能格式化和更干净的外观。我将添加它作为一个评论。哦我无法评论。对于问题的“当前时间”部分,您可以从
loc_dt=pytz.utc.localize(datetime.utcnow())
开始,而不是从constant@patricksurry:在“我不想使用外部库”中回答了“当前时间”部分。我只想使用本机库。那我该怎么办呢?在2021年,我会说这是最好的方法。我不想使用外部库。我只想使用本机库。那我该怎么办?pytz和datetime是本地的libraries@DavidB. 不,pytz是第三方库。幸运的是,
zoneinfo
附带了Python 3.9的标准库,请参见我的答案;-)其“亚洲/加尔各答”而非“亚洲/印度”,获取所有可用的tzs:
pytz。所有时区
@ShirishShukla感谢您的关注。我已经编辑了我的答案,将加尔各答而不是印度包括在内。我不想使用外部图书馆。我只想使用本机库。那我该怎么办呢?使用
datetime.now(tz=gettz('US/Pacific'))
有什么问题吗?@LeonardRick这很好!实际上,我也想添加这个选项,但从未花时间。谢谢提醒;-)
import pandas as pd

t = pd.Timestamp.now('UTC') #pull UTC time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_UTC_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format

t = pd.Timestamp.now(tz='US/Eastern') #pull Eastern (EDT or EST, as current) time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_EAST_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format

print(f"The current UTC time is: {now_UTC_rounded} (rounded to the nearest 10 min)")
print(f"The current US/Eastern time is: {now_EAST_rounded} (rounded to the nearest 10 min)")
The current UTC time is: 1800 (rounded to the nearest 10 min)
The current US/Eastern time is: 1400 (rounded to the nearest 10 min)