LoginSignup
52
28

More than 5 years have passed since last update.

Python: datetimeで確実に日本時間を取得する方法

Last updated at Posted at 2018-05-17

概要

  • Pythonのdatetimeで確実に日本時間を取得したい。
  • datetime.datetime.now()などdatetimeで今の時刻や日付を取得しようとすると、環境次第では日本時間以外が取得されてしまう。
  • ローカル開発環境では日本時間だったのにデプロイしたらUTCになってたりする。
  • Python2.7でやってます。

方法1: pytzの利用

datetime.datetime.now()の引数にpytz.timezone()で東京を指定する。

method1.py

# coding: utf-8

import datetime
import pytz


now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))


>>> now
2018-05-17 13:26:50.224163+09:00

方法2: UTCとの差分を計算

JSTとUTCの差分は+9時間なので、UTC時間を取得して+9時間する。

method2.py

# coding: utf-8

import datetime


# JSTとUTCの差分
DIFF_JST_FROM_UTC = 9
now = datetime.datetime.utcnow() + datetime.timedelta(hours=DIFF_JST_FROM_UTC)


>>> now
2018-05-17 13:26:50.224208

52
28
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
52
28