1
3

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.

pytzを使わずにAsia/Tokyoのタイムゾーンを設定する

Last updated at Posted at 2019-01-28

環境

  • OS: Debian GNU/Linux 9 (stretch)
  • python: 3.5.3

参考サイト

実装(python3系)

tz.py
from datetime import datetime, timezone, timedelta

jp = timezone(timedelta(hours=9), 'Asia/Tokyo')

print(datetime.now(tz=jp).strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
> 2019-01-27T16:36:11.831894+0900

print(datetime.strptime('2019-01-25 19:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=jp).strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
> 2019-01-25T19:00:00.000000+0900

実装(python2系)

timezone/jp.py
from datetime import tzinfo, timedelta

class JP(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=9)

    def dst(self, dt):
        return timedelta(0)

    def tzname(self, dt):
        return 'Asia/Tokyo'

利用側

tz.py
from datetime import datetime
from timezone.jp import JP

print(datetime.now(tz=JP()).strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
> 2019-01-27T16:36:11.831894+0900

print(datetime.strptime('2019-01-25 19:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=JP()).strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
> 2019-01-25T19:00:00.000000+0900
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?