この記事の目的
- datetimeにタイムゾーン情報を付与して出力する方法を知る
awareとnaive
datetime 型にはタイムゾーンの情報を持たない naive と、タイムゾーンの情報を持つ aware な datetime 型がある
なぜタイムゾーンが必要?
タイムゾーン情報を設定していない場合、ローカルマシン側ではJST(日本標準時)で、サーバ側ではUTC(協定世界時)となる可能性がある
実装例(3種類)
datetime.py
from datetime import datetime, timedelta, timezone
from dateutil import tz
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("Asia/Tokyo"))
print(now)
# 2022-10-27 13:51:55.293383+09:00
JST = tz.gettz("Asia/Tokyo")
dt = datetime.now(JST)
print(dt)
# 2022-10-27 13:51:55.293613+09:00
JST = timezone(timedelta(hours=+9), "JST")
time = datetime.now(JST)
print(time)
# 2022-10-27 13:51:55.293648+09:00
システムにあう方法で出力しよう!!