📘
pythonでUTCの日時文字列をJSTに変換する
問題
- APIから、日時情報として
2023-01-06T21:02:54.87
の文字列を受け取った- 仕様上、UTCである
- 分かりやすさのため、日本時間で扱いたい
- どうするか
対応
import datetime
from dateutil import tz
def convert_exec_date(raw: str):
jst = tz.gettz("Asia/Tokyo")
d = datetime.datetime.strptime(raw, '%Y-%m-%dT%H:%M:%S.%f')
return d.astimezone(jst)
def test_convert_exec_date():
assert str(convert_exec_date("2023-01-06T21:02:54.87")) \
== "2023-01-07 06:02:54.870000+09:00"
Discussion