Pythonで日付と時間を扱う際、特に異なるタイムゾーン間での変換は頻繁に行われます。ここでは、UTCとJSTの間での変換方法について説明します。
必要なライブラリ
まず、dateutil
ライブラリが必要です。これはPythonで日付と時間を扱うための強力な拡張機能を提供します。インストールは以下のコマンドで行えます。
pip install python-dateutil
タイムゾーンの設定
次に、UTCとJSTのタイムゾーンを設定します。
from datetime import datetime
from dateutil import tz
JST = tz.gettz('Asia/Tokyo')
UTC = tz.gettz('UTC')
datetimeオブジェクトの生成
以下の例では、UTCのタイムゾーンを持つaware
なdatetimeを作成します。
A = datetime(2021, 4, 1, 11, 22, 33, tzinfo=UTC)
print(A.isoformat()) # '2021-04-01T11:22:33+00:00'
また、タイムゾーン情報を持たないnative
なdatetimeも作成できます。
B = datetime(2021, 4, 1, 11, 22, 33)
print(B.isoformat()) # '2021-04-01T11:22:33'
タイムゾーンの変換
astimezone
メソッドを使用して、datetimeオブジェクトのタイムゾーンを変換できます。
# UTCからJSTへ
print(A.astimezone(JST)) # '2021-04-01T20:22:33+09:00'
# JSTからUTCへ
C = datetime(2021, 4, 1, 20, 22, 33, tzinfo=JST)
print(C.astimezone(UTC)) # '2021-04-01T11:22:33+00:00'
以上がPythonでUTCとJSTを変換する基本的な方法です。さまざまな日付と時間の操作を行う際に、これらのテクニックが役立つことでしょう。.