【问题标题】:How to convert time in this format to local time zone?如何将这种格式的时间转换为本地时区?
【发布时间】:2018-10-29 19:28:32
【问题描述】:

我想在 python 的本地时区(本例中为 EDT)中将这次的 Sat, 19 May 2018 16:32:56 +0000 转换为 20180519-113256。谁能教我怎么做?

PS.,以下示例显示了如何将时间转换为本地时区。但我不确定如何解析Sat, 19 May 2018 16:32:56 +0000

Convert UTC datetime string to local datetime with Python

【问题讨论】:

标签: python datetime-format time-format


【解决方案1】:

您可以选择任何您想要的时区:

import pytz
from datetime import datetime

s = 'Sat, 19 May 2018 16:32:56 +0000'
dt = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z')
tz = pytz.timezone('America/Chicago')
new_s = dt.astimezone(tz).strftime('%Y%m%d-%H%M%S')

【讨论】:

    【解决方案2】:

    对我来说这是可行的:

    from datetime import datetime
    from dateutil import tz
    
    def convert(date, from_zone = 'UTC', to_zone='America/New_York'):
        from_zone = tz.gettz(from_zone)
        to_zone = tz.gettz(to_zone)
        date = date.replace(tzinfo=from_zone)
        central = date.astimezone(to_zone)
        return date
    
    s = "Sat, 19 May 2018 16:32:56 +0000"
    d = datetime.strptime(s, '%a, %d %B %Y %H:%M:%S +%f')
    d = convert(d)
    

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 2019-05-31
      相关资源
      最近更新 更多