Created
July 7, 2012 06:32
-
-
Save raimon49/3065094 to your computer and use it in GitHub Desktop.
動的にtzinfoサブクラスを作ってdatetimeオブジェクトを異なるタイムゾーンに変換する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from datetime import * | |
def create_tzinfo(name, offset_hours=0, offset_dst=0): | |
my_tzinfo = type(name, (tzinfo, ), {}) | |
my_tzinfo.utcoffset = lambda self, dt: timedelta(hours=offset_hours) | |
my_tzinfo.dst = lambda self, dt: timedelta(offset_dst) | |
my_tzinfo.tzname = lambda self, dt: name | |
return my_tzinfo | |
def to_jst(): | |
# tzinfoのサブクラスを生成 | |
UTC = create_tzinfo('UTC', 0) | |
JST = create_tzinfo('JST', 9) | |
# UTC -> JSTに変換 | |
utc_datetime = datetime.now(UTC()) | |
jst_datetime = utc_datetime.astimezone(JST()) | |
print('from(UTC): %s \nto(JST): %s' % (utc_datetime, jst_datetime)) | |
if __name__ == '__main__': | |
to_jst() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment