显示不同时区的时间
- 2024-12-09 08:29:00
- admin 原创
- 133
问题描述:
有没有一种优雅的方式可以显示另一个时区的当前时间?
我希望拥有一些具有以下总体精神的东西:
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')>))
解决方案 1:
更简单的方法:
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')
解决方案 2:
您可以使用pytz库:
>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = pytz.timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = pytz.timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print loc_dt.strftime(fmt)
2002-10-27 06:00:00 EST-0500
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
解决方案 3:
Python 3.9(或更高版本):使用标准库中的zoneinfo :
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_local = datetime.now().astimezone()
now_UTC = datetime.now(tz=timezone.utc)
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
通过backports模块使用,也可以使用dateutil。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
解决方案 4:
一种方法是通过 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'
解决方案 5:
该问题的最短答案可以是:
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
这将打印:
2019-06-20 12:48:56.862291+05:30
解决方案 6:
该脚本利用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
解决方案 7:
这是我的实现:
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')
解决方案 8:
我需要所有时间的时间信息,因此我的服务器上有一个简洁的 .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
这里的源代码是我 github 上的一个 .py 文件:
https://github.com/SpiRaiL/timezone
或者直接文件链接:
https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py
文件中有一个这样的列表:只需在您想要打印的位置输入“p”。如果您希望特别标记,请输入“h”代表您自己的时区。
(' ','America/Adak'), (' ','Africa/Abidjan'), (' ','Atlantic/Azores'), (' ','GB'),
(' ','America/Anchorage'), (' ','Africa/Accra'), (' ','Atlantic/Bermuda'), (' ','GB-Eire'),
(' ','America/Anguilla'), (' ','Africa/Addis_Ababa'), (' ','Atlantic/Canary'), (' ','GMT'),
(' ','America/Antigua'), (' ','Africa/Algiers'), (' ','Atlantic/Cape_Verde'), (' ','GMT+0'),
(' ','America/Araguaina'), (' ','Africa/Asmara'), (' ','Atlantic/Faeroe'), (' ','GMT-0'),
(' ','America/Argentina/Buenos_Aires'), (' ','Africa/Asmera'), (' ','Atlantic/Faroe'), (' ','GMT0'),
(' ','America/Argentina/Catamarca'), (' ','Africa/Bamako'), (' ','Atlantic/Jan_Mayen'), (' ','Greenwich'),
(' ','America/Argentina/ComodRivadavia'), (' ','Africa/Bangui'), (' ','Atlantic/Madeira'), (' ','HST'),
(' ','America/Argentina/Cordoba'), (' ','Africa/Banjul'), (' ','Atlantic/Reykjavik'), (' ','Hongkong'),
解决方案 9:
datetime
可以通过从datetime
和导入模块来指定时区pytx
。
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"))
解决方案 10:
我最终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 分钟,但仍然可以获得匹配。
只是展示功能 - 显然,如果您不想的话,您不需要使用该回合!
解决方案 11:
如果您想要一种不需要导入 pytz 或任何特定时区库的方法,您可以通过仅导入 datetime 的方式来实现。通过使用 datetime 获取当前 UTC 时间,然后添加 timezone 修饰符,可以实现任何所需的时区。
例如,纽约的时区比 UTC 时间晚 4 小时,即 UTC-04:00。这意味着我们可以使用此代码查找纽约的当前时间:
import datetime
utc_time = datetime.datetime.utc(now)
tz_modifier = datetime.datetime.timedelta(hours=-4)
tz_time = utc_time + tz_modifier
print(tz_time)
为了使其更“优雅”,可以使用这种方法:
from datetime import datetime, timedelta
utc = datetime.utcnow()
print("China time {}".format(utc+timedelta(hours=8)))
print("Greece time {}".format(utc+timedelta(hours=3)))
print("Hawaii time {}".format(utc+timedelta(hours=-10)))
这种方法的缺点是必须已经知道时区的实际 UTC 差异。