【问题标题】:Conversion of timezone of datetime.timedatetime.time的时区转换
【发布时间】: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


【解决方案1】:

在输入字符串中添加适当的日期,这将按您的预期工作:

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

【讨论】:

  • 我应该明确添加任何临时日期以转换时区吗?
  • @Saqib:这取决于,这就是我写合适的日期的原因。如果您有一个 DST 时区,您可以根据您选择的日期获得不同的 UTC 偏移量。
猜你喜欢
  • 2013-05-12
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 2016-05-16
  • 2021-04-24
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多