LoginSignup
0
0

More than 5 years have passed since last update.

[Python3.5]datetimeオブジェクトのタイムゾーンを扱う

Last updated at Posted at 2017-09-29

utcからjstに変換というより、datetimeオブジェクトのtimezoneを扱う方法です。

naiveなUTCのdatetimeオブジェクトからからJSTに変換

環境

  • python3.5
  • windows10

datetimeオブジェクトのawareとnaive

datetimeオブジェクトにはawareとnaiveという二つの状態がある

- aware
TimeZone情報を持つdatetimeオブジェクト
- naive
TimeZone情報を持たないdatetimeオブジェクト

datetimeオブジェクトに対して明示的にUTCであるというTimeZone情報を持たせて
naiveからawareにする必要がある。

その際にはpytzライブラリを使う
ちなみにPython3.5 のこちらのドキュメントには以下の内容が記載されている。

pytz

pytz ライブラリは Python に IANA タイムゾーンデータベース (オルソンデータベースとしても知られています) を持ってきます、そしてそれの利用が推奨されます。

コード

以下がnavieからawareに変換しutcであるという情報を持ったtimezoneオブジェクトをJSTに変換する処理

from pytz import timezone as tz, utc
utc_time = utc.localize(utc_naive)
jst_time = utc_time.astimezone(tz("Asia/Tokyo"))
0
0
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
0