LoginSignup
3
2

More than 1 year has passed since last update.

Python 3 UTCエポックから日本標準時変換

Last updated at Posted at 2021-09-03

とある通信機器からUTCエポックを受信する機会があった。Python3での日本標準時への変換方法をPythonライブラリーリファレンスで調べた。

方法

変換方法は1つではないが、datetime モジュールとサードパーティーライブラリー dateutil パッケージを使用する方法がある。 dateutil は標準では無いので実行環境にない場合はインストールが必要。

dateutil パッケージのインストールコマンド

pip install python-dateutil

変換コード


from datetime import datetime
from dateutil import tz

utc_epoch = 1630557969 # UTCエポックの一例
time_zone = tz.gettz('Asia/Tokyo')
jst_time = datetime.fromtimestamp(utc_epoch, time_zone)

UTCエポックは少数部も含むが、ここではetc_epoch に整数部だけの数値を代入。tz.gettz(name=None) メソッドは引数にIANAタイムゾーンの文字列表現を取って tzinfo オブジェクトを返す。引数の Asia/Tokyo で日本標準時を意味する。 Ameria/NewYork , Europe/Paris など別のタイムゾーンオブジェクトを受け取ることも可能。datetime.fromtimestamp(timestamp, tz=None) メソッドは第一引数にPOSIXタイム, 第二引数にオブジェクトを受けて datetime オブジェクトを返す。

余談

エポックとは時刻の基準のこと。Windows、ほとんどのUnixシステムでは1970年1月1日0時0分0秒(UTC)を基準にとっている。Python 3では下記のようにしてエポックを調べられる。エポック時間とは、この基準からの経過秒を示す。Unixタイムと表現されることもある。

import time

print(time.gmtime(0))

参考

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