Python
datetime
Python3

Pythonの UTC ⇔ JST、文字列(UTC) ⇒ JST の変換とかのメモ

More than 3 years have passed since last update.


awareなdatetimeオブジェクト(UTC)をJSTへ変換

>>> from pytz import timezone

>>> from datetime import datetime
>>> utc_now = datetime.now(timezone('UTC'))
>>> print(utc_now)
2016-03-20 01:07:29.056724+00:00
>>> jst_now = utc_now.astimezone(timezone('Asia/Tokyo'))
>>> print(jst_now)
2016-03-20 10:07:29.056724+09:00


naiveなdatetimeオブジェクトをUTC,JSTへ変換

>>> from pytz import timezone

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now)
2016-03-20 10:14:41.929706
>>> utc_now = timezone('UTC').localize(now)
>>> print(utc_now)
2016-03-20 10:14:41.929706+00:00
>>> jst_now = timezone('Asia/Tokyo').localize(now)
>>> print(jst_now)
2016-03-20 10:14:41.929706+09:00


文字列の日付(UTC)をJSTへ変換

>>> from pytz import timezone

>>> from dateutil import parser
>>> utc_string = "Sat Mar 19 06:17:57 +0000 2016"
>>> jst_time = parser.parse(utc_string).astimezone(timezone('Asia/Tokyo'))
>>> print(jst_time)
2016-03-19 15:17:57+09:00


ISO表記へ変換

>>> from datetime import datetime

>>> now = datetime.now()
>>> print(now)
2016-03-21 00:14:06.135787
>>> iso_now = now.isoformat()
>>> print(iso_now)
2016-03-21T00:14:06.135787

参考:

Python の datetime オブジェクトと Unix 時間の相互変換方法のまとめ

Pythonでタイムゾーンを扱うメモ

公式ドキュメント#datetime.isoformat