显示不同时区的时间 [英] Display the time in a different time zone

查看:51
本文介绍了显示不同时区的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种优雅的方式来显示另一个时区的当前时间?

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

cur = <获取当前时间,可能是datetime.datetime.now()>print("当地时间{}".format(cur))print("太平洋时间{}".format(<类似 cur.tz('PST')>))print("以色列时间{}".format(<类似 cur.tz('IST')>))

解决方案

您可以使用 pytz 库:

<预><代码>>>>从日期时间导入日期时间>>>进口pytz>>>utc = pytz.utc>>>UTC区域'世界标准时间'>>>东部 = pytz.timezone('美国/东部')>>>东区'美国/东部'>>>阿姆斯特丹 = pytz.timezone('欧洲/阿姆斯特丹')>>>fmt = '%Y-%m-%d %H:%M:%S %Z%z'>>>loc_dt = Eastern.localize(datetime(2002, 10, 27, 6, 0, 0))>>>打印 loc_dt.strftime(fmt)2002-10-27 06:00:00 EST-0500>>>ams_dt = loc_dt.astimezone(阿姆斯特丹)>>>ams_dt.strftime(fmt)'2002-10-27 12:00:00 CET+0100'

Is there an elegant way to display the current time in another time zone?

I would like to have something with the general spirit of:

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')>))

解决方案

You could use the pytz library:

>>> 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'

这篇关于显示不同时区的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆