如何解决datetime.time 的时区转换
我正在使用箭头库编写 Python 代码,以将字符串(不带日期)中的时区(默认为 UTC)转换为另一个时区。
示例字符串值为:18:30+0000
代码片段是:
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'))
解决方法
向输入字符串添加适当的日期,这将按您的预期工作:
import arrow
start = '2021-02-01 18:30+0000'
start_time = arrow.get(start)
print(start_time.to('Australia/Melbourne').format('hh:mm A ZZ'))
# 05:30 AM +11:00
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。