在Python中将UTC字符串转换为本地日期时间字符串?

时间:2014-01-16 06:42:53

标签: python datetime

我没有时区的名称,只有偏移值,例如+0400

我有UTC的日期时间字符串:例如2014-01-07T09:29:35Z

我想在当地时间使用字符串,例如2014-01-07T13:29:35

怎么做?

2 个答案:

答案 0 :(得分:1)

您可以编写一个函数来转换字符串格式。

from datetime import datetime, timedelta
old_time = '2014-01-07T09:29:35Z'

def time_converter(old_time, time_zone):
    time_zone = float(time_zone[:3] + ('.5' if time_zone[3] == '3' else '.0'))
    str_time = datetime.strptime(old_time, "%Y-%m-%dT%H:%M:%SZ")
    return (str_time + timedelta(hours=time_zone)).strftime("%Y-%m-%dT%H:%M:%SZ")

if __name__ == '__main__':
    for time_zone in ('+0400', '+0430', '-1400'):
        print(time_converter(old_time, time_zone))

输出:

2014-01-07T13:29:35Z
2014-01-07T13:59:35Z
2014-01-06T19:29:35Z

答案 1 :(得分:0)

您还可以创建用于创建时区感知日期时间对象的时区类:

from datetime import tzinfo, timedelta, datetime

class myTimeZone(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=4)
    def dst(self, dt):
        return timedelta(hours=0)

class utcTimeZone(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=0)
    def dst(self, dt):
        return timedelta(hours=0)

d = datetime.strptime("2014-01-07T09:29:35Z","%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=utcTimeZone())
print(d.astimezone(myTimeZone()).isoformat())   # Prints '2014-01-07T13:29:35+04:00'