如何将此格式的时间转换为本地时区?

时间:2018-05-19 15:28:58

标签: python datetime-format time-format

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

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

Convert UTC datetime string to local datetime with Python

2 个答案:

答案 0 :(得分:0)

对我来说这很有效:

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)

答案 1 :(得分:0)

您可以选择所需的任何时区:

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')