LoginSignup
1
2

More than 5 years have passed since last update.

pythonでタイムゾーンを意識して日時を扱う方法

Posted at

はじめに

pythonでdatetimeモジュールを使って日時を扱う時はタイムゾーンを意識する必要がある場合があります。
でも、変換方法を毎回調べてる自分がいたので、まとめておこうと思った次第。

TL;DR

from datetime import datetime, timezone, timedelta

JST = timezone(timedelta(hours=+9), 'JST')
c = datetime(2019, 4, 1, 23, 0, 0).replace(tzinfo=JST)
print(c)    # 2019-04-01 23:00:00+09:00

now = 1554127200    # 2019-04-01 23:00:00(日本時間)のunix timestamp
c = datetime.fromtimestamp(now, JST)
print(c)            # 2019-04-01 23:00:00+09:00

何も指定しないとこうなる

from datetime import datetime

year = 2019
month = 4
day = 1
hour = 23

c = datetime(year, month, day, hour, 0, 0)
print(c)    # 2019-04-01 23:00:00

一見良さそうです。
ただし、これは2019-04-01 23:00:00がどこのタイムゾーンの話なのか分かりません。

UNIXタイムスタンプからの変換結果も、そのまま出力しようとするとUTCでの日時が出てきます。

from datetime import datetime

now = 1554127200    # 2019-04-01 23:00:00(日本時間)のunix timestamp
c = datetime.fromtimestamp(now)
print(c)            # 2019-04-01 14:00:00 <- UTC

timezone

datetime.timezoneは、タイムゾーンを扱うクラスです。

datetimeオブジェクトは、自身がタイムゾーンの情報を持つ場合(aware)と、持たない場合(naive)があります。
明示的に指定しないとnaiveとなり、タイムゾーン情報を持たせる場合はreplaceメソッドを使用します。

from datetime import datetime, timezone, timedelta

year = 2019
month = 4
day = 1
hour = 23

JST = timezone(timedelta(hours=+9), 'JST')
c = datetime(year, month, day, hour, 0, 0).replace(tzinfo=JST)
print(c)            # 2019-04-01 23:00:00+09:00

now = 1554127200    # 2019-04-01 23:00:00(日本時間)のunix timestamp
c = datetime.fromtimestamp(now, JST)
print(c)            # 2019-04-01 23:00:00+09:00

UTC についてはdatetime.timezone.utcが標準で用意されています。

from datetime import datetime, timezone

year = 2019
month = 4
day = 1
hour = 23

c = datetime(year, month, day, hour, 0, 0).replace(tzinfo=timezone.utc)
print(c)            # 2019-04-01 23:00:00+00:00

now = 1554127200    # 2019-04-01 23:00:00(日本時間)のunix timestamp
c = datetime.fromtimestamp(now, timezone.utc)
print(c)            # 2019-04-01 14:00:00+00:00

おわりに

datetimeモジュールのみを使用することを想定しています。
別のライブラリを使用する例もありますが、UTCとJSTだけを扱えれば良いのであれば上記の形で十分かと。
(日本でも夏時間を扱うとなったら話は別ですが...)

1
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
1
2