Convert UTC string to local datetime string in python?
本问题已经有最佳答案,请猛点这里访问。
我没有时区的名称,只有一个偏移值,如
我有UTC的日期时间字符串:如
我想在本地时间输入一个字符串,比如
这该怎么做?
您可以编写一个函数来转换字符串格式。
1 2 3 4 5 6 7 8 9 10 11 | 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)) |
输出:
1 2 3 | 2014-01-07T13:29:35Z 2014-01-07T13:59:35Z 2014-01-06T19:29:35Z |
您还可以创建时区类来创建时区感知日期时间对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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' |