Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

  • 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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away