created: 2019-01-12T14:42:03.000Z

PythonでTimezone Aware(Jst)なdatetimeを作る

ググっても簡単なのが出てこなかったのでメモ

環境は python 3.6.7

こんな定義で引数に渡した日付時間がJSTのdatetimeになる

from pytz import timezone

def jst_datetime(*args):
    rest = [0] * (7 - len(args))
    return datetime(*args, *rest, timezone('Asia/Tokyo'))

使い方

datetimeと同じ

got = jst_datetime(2019, 1, 5, 2, 0)
t.assertIs(got.hour, 2)
t.assertIs(got.day, 5)
t.assertEqual(str(got.tzinfo), 'Asia/Tokyo')

got2 = jst_datetime(2019, 1, 5, 2)
t.assertEqual(got, got2)
got3 = jst_datetime(2019, 1, 5, 2, 0, 0)
t.assertEqual(got, got3)

参考

経済数学の直観的方法 確率・統計編 (ブルーバックス)
[ad] 経済数学の直観的方法 確率・統計編 (ブルーバックス)
長沼伸一郎 (Kindle版)