Python 不安裝額外套件轉換時區

目標

將符合 ISO 8601 格式的 1987-09-12T09:12:00+08:00 字串轉換成 UTC 時區的 datetime.datetime 物件。

步驟

Python 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from datetime import datetime, timezone
def 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:00
if __name__ == '__main__':
main()

Python 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from datetime import datetime, timedelta, tzinfo
class 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:00
if __name__ == '__main__':
main()