代码之家  ›  专栏  ›  技术社区  ›  BruceWayne

将hh:mm utc+2转换为hh:mm[非utc]

  •  0
  • BruceWayne  · 技术社区  · 8 年前

    我有一本包含时间的字典,像

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

    我怎么能抽出时间改变它在哪个区域( UTC+2 , UTC , UTC+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 回复  |  直到 8 年前
        1
  •  1
  •   abarnert    8 年前

    日期很好,我可以把它去掉。

    总比把它变成一根细绳,然后试图咀嚼它好,只要把它作为一个 datetime 对象,直到需要字符串,然后使用 strftime 方法以按需设置其格式。例如:

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

    或者,如果你使用f字符串或者 str.format ,甚至可以将其直接放入 日期时间 对象:

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

    我不知道为什么时间似乎是一个范围?

    事实上,不是。默认值 str 显示格式 日期时间 对象基于 ISO 8601 . 对于了解他们时区的当地人来说 UTC offset 在这个时候,它被包括作为一个 +02:00 -05:00 最后。

    我期待24小时的格式输出。

    这已经是 STR 输出。

    但更重要的是,当你问的时候,这就是你得到的。 strftime 对于 %H . (如果你想要12小时,那是 %I )


    一。但不是所有选项的默认设置,比如 T 作为时间分隔符。如果你想要,你必须打电话给 isoformat 方法。