0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[datetime] タイムゾーンを意識しよう

Last updated at Posted at 2023-01-13

この記事の目的

  • 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

システムにあう方法で出力しよう!!

参考

[Python] datetime とタイムゾーンについてのメモ

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?