【发布时间】:2023-03-19 15:20:01
【问题描述】:
我正在编写 Python 代码,使用箭头库将字符串(不带日期)中的时区(默认为 UTC)转换为另一个时区。
示例字符串值为:18:30+0000
代码sn-p是:
start = '18:30+0000'
start_time = arrow.get(start,'hh:mmZ')
print(start_time.format('hh:mm A ZZ'))
print(start_time.to('Australia/Melbourne').format('hh:mm A ZZ'))
# This should print 05:30 AM +11:00 - but showing 04:09 AM +09:39
我也尝试过转换到其他时区。
print(start_time.to('Europe/London').format('hh:mm A ZZ'))
# This should print 06:30 PM +00:00 - but showing 06:28 PM -00:01
现在获取 UTC,然后将其转换为不同的时区工作得很好
print(arrow.utcnow().to('Australia/Melbourne').format('hh:mm A ZZ'))
解决方案: 如果我们没有日期值,我们必须为转换添加临时日期值。
def convert_timezone(time_to_convert,timezone):
time_to_convert='20111111 '+time_to_convert
return arrow.get(time_to_convert).to(timezone)
print(convert_timezone('18:30+0000','Australia/Melbourne').format('hh:mm A ZZ'))
【问题讨论】:
-
时区转换仅对时间没有多大意义,没有日期(想想 DST)。我怀疑箭头会退回到您尝试转换到的时区的 LMT(本地平均时间)。尝试对包含日期的字符串进行相同操作,这应该可以正常工作。
-
旁注:afaik,
arrow内部使用dateutil,而不是pytz。 -
我明白了你的想法。基本上,逻辑是在用户每周有空参加会议时将时间与时区一起存储。保存日期和时间将无济于事。但是,您给出的 LMT 逻辑是正确的箭头是使用 LMT 作为时区。
-
是的,存储日期不会花费您几个字节。如果它对用户无关紧要,就不要打印它。但在内部,你会想要拥有它。
标签: python python-3.x python-datetime pytz python-arrow