Python 不安裝額外套件轉換時區 發表於 2016-05-01 | 目標將符合 ISO 8601 格式的 1987-09-12T09:12:00+08:00 字串轉換成 UTC 時區的 datetime.datetime 物件。 步驟Python 3123456789101112131415from datetime import datetime, timezonedef main(): dt_format = '%Y-%m-%dT%H:%M:%S%z' dt_str = '1987-09-12T09:12:00+08:00' dt = datetime.strptime(dt_str.replace('+08:00', '+0800'), dt_format) utc_dt = dt.astimezone(timezone.utc) print(dt) # 1987-09-12 09:12:00+08:00 print(utc_dt) # 1987-09-12 01:12:00+00:00if __name__ == '__main__': main() Python 21234567891011121314151617181920212223242526272829303132333435363738from datetime import datetime, timedelta, tzinfoclass UTC(tzinfo): def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return 'UTC' def dst(self, dt): return timedelta(0)class GMT8(tzinfo): def dst(self, dt): return timedelta(0) def tzname(self, dt): return 'GMT +8' def utcoffset(self, dt): return timedelta(hours=8) + self.dst(dt)def main(): dt_format = '%Y-%m-%dT%H:%M:%S' dt_str = '1987-09-12T09:12:00+08:00' naive_dt = datetime.strptime(dt_str.replace('+08:00', ''), dt_format) dt = naive_dt.replace(tzinfo=GMT8()) utc_dt = dt.astimezone(UTC()) print(dt) # 1987-09-12 09:12:00+08:00 print(utc_dt) # 1987-09-12 01:12:00+00:00if __name__ == '__main__': main()