将HH:MM UTC + 2转换为HH:MM [不是UTC]

时间:2018-06-22 21:23:11

标签: python timezone

我有一本包含时间的字典,其设置类似于

{ '2018-06-22': { 24: { 24: { 'Team1': 'Nigeria',
                              'Team2': 'Iceland',
                              'Time': '18:00',
                              'Timezone': 'UTC+ ... }}

我该如何利用时间从其所在的任何区域(UTC+2UTCUTC+3等)更改为例如美国芝加哥(UTC-5) ?

我尝试使用solution here,但得到1900-01-01 10:00:00-05:00。日期还可以,我可以删除它。我不确定为什么时间似乎在一定范围内?我原本希望24小时格式输出。

from datetime import datetime
from dateutil import tz

def update_timezone(time, old_zone, new_zone):
    """
    Takes an old timezone and converts to the new one
    """
    from_zone = tz.gettz(old_zone)
    to_zone = tz.gettz(new_zone)

    utc = datetime.strptime(time, "%H:%M")

    utc = utc.replace(tzinfo=from_zone)
    central = utc.astimezone(to_zone)
    return central

print(update_timezone("18:00", "UTC+3","UTC-5"))

输出:

  

1900-01-01 10:00:00-05:00

所需的输出:

  

11:00

1 个答案:

答案 0 :(得分:1)

  

现在还可以,我可以删除它。

与其转换为字符串然后尝试对其进行修改,不如将其保留为datetime对象,直到需要一个字符串为止,然后使用strftime方法对其进行格式化即可。例如:

>>> dt.strftime('%H:%M')
10:00

或者,如果您使用的是f字符串或str.format,甚至可以将其直接放在datetime对象的格式规范中:

>>> print(f'The time sponsored by Accurist is {dt:%H:%M}, precisely.')
The time sponsored by Accurist is 10:00, precisely.
  

我不确定为什么时间似乎在一定范围内?

实际上不是。用于显示str对象的默认datetime格式基于ISO 8601 1 对于在当地时间知道其时区UTC offset的本地时间问题,最后以+02:00-05:00的形式出现。

  

我希望输出24小时格式。

这已经是str输出的默认值。

但是,更重要的是,这就是您向strftime索取%H时得到的。 (如果您想要12小时,那就是%I。)


1。但不是所有选项的默认设置,例如T作为时间分隔符。如果需要,您必须调用isoformat方法。