128
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-03-20

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

128
98
1

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
128
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?