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)

参考

勉強の戦略――9割の「努力」をやめ、真に必要な一点に集中する
[ad] 勉強の戦略――9割の「努力」をやめ、真に必要な一点に集中する
岡 健作 (単行本)