是否有一种优雅的方式在另一个时区显示当前时间?
我想拥有一般精神:
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')>))
答案 0 :(得分:101)
一种更简单的方法:
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')
答案 1 :(得分:51)
您可以使用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'
答案 2 :(得分:9)
通过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'
答案 3 :(得分:7)
Python 3.9 :pytz
是deprecated,因为您现在在标准库中有zoneinfo:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
now_UTC = datetime.now(tz=timezone.utc)
now_local = now_UTC.astimezone(None)
pacifictz, israeltz = ZoneInfo('US/Pacific'), ZoneInfo('Israel')
now_pst, now_ist = now_UTC.astimezone(pacifictz), now_UTC.astimezone(israeltz)
print(f"Local time {now_local.isoformat()}")
print(f"Pacific time {now_pst.isoformat()}")
print(f"Israeli time {now_ist.isoformat()}")
# Local time 2020-08-28T09:03:30.710001+02:00
# Pacific time 2020-08-28T00:03:30.710001-07:00
# Israeli time 2020-08-28T10:03:30.710001+03:00
Python的旧版本 :您可以通过backports模块使用zoneinfo
,也可以使用dateutil。 dateutil的tz.gettz
遵循与zoneinfo.ZoneInfo
相同的语义:
from dateutil.tz import gettz
pacifictz, israeltz = gettz('US/Pacific'), gettz('Israel')
now_pst, now_ist = now_UTC.astimezone(pacifictz), now_UTC.astimezone(israeltz)
print(f"Pacific time {now_pst.isoformat()}")
print(f"Israeli time {now_ist.isoformat()}")
# Pacific time 2020-08-28T00:03:30.710001-07:00
# Israeli time 2020-08-28T10:03:30.710001+03:00
答案 4 :(得分:2)
这是我的实施:
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')
答案 5 :(得分:1)
此脚本使用to_datatime
和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()))
答案 6 :(得分:0)
您可以查看this question。
或尝试使用pytz。在这里,您可以找到包含一些使用示例的安装指南。
答案 7 :(得分:0)
问题的最短答案可能是:
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
这将打印:
2019-06-20 12:48:56.862291 + 05:30
答案 8 :(得分:0)
可以通过从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/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
答案 9 :(得分:0)
我最终在我的代码中大量使用了 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 分钟,但仍然可以匹配。
只是炫耀功能 - 如果您不想,显然您不需要使用该回合!
答案 10 :(得分:-1)
我需要所有时间的时间信息,所以我在我的服务器上有这个简洁的.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
在文件中是这样的列表: 只要把一个&#39; p&#39;在你想要打印的地方。 放一个&#39; h&#39;如果你想特别标记它,你自己的时区。
(' ','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'),