LoginSignup
1
1

More than 5 years have passed since last update.

[Python]UNIX秒(UTC)をISO8601(JST)に変換する

Posted at

用途

データとしてはUTCのエポック秒を持ちつつビューには日本時間の見やすい表記にしたい場合

やること

datetime のオブジェクトでタイムゾーンを操作して最終的に文字列や数値として書き出す

UNIX(UTC) to ISO8601(JST)

from datetime import datetime, timezone, timedelta


JST = timezone(timedelta(hours=+9), 'JST')

# [サンプル]UNIX秒(UTC)を生成
epoch = int(datetime.now(timezone.utc).strftime('%s%f')) // 1000000

# datetime(JST)に変換
dt = datetime.fromtimestamp(epoch).replace(tzinfo=timezone.utc).astimezone(tz=JST)

# ISO8601表記
print(dt.isoformat()) 

# あるいは任意のフォーマット
print(dt.strftime('%Y-%m-%d %H:%M:%S'))

ISO8601(JST) to UNIX(UTC)

from datetime import datetime, timezone, timedelta


JST = timezone(timedelta(hours=+9), 'JST')

# [サンプル]時刻を表す文字列(JST)を生成
now = datetime.now(JST).strftime('%Y-%m-%d %H:%M:%S')

# datetime(UTC)に変換
dt = datetime.strptime(now, '%Y-%m-%d %H:%M:%S').astimezone(tz=JST).replace(tzinfo=JST).astimezone(tz=timezone.utc)

# UNIX時間(UTC)
print(int(dt.strftime('%s%f')) // 1000000)
1
1
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
1