Last active
July 4, 2016 00:54
-
-
Save magnetikonline/bb7dc1809d3b22ad311a492bc982edb0 to your computer and use it in GitHub Desktop.
Fun with Python datetime timezones.
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 datetime | |
import timezone | |
def main(): | |
my_time = datetime( | |
year = 2016, | |
month = 1, | |
day = 1, | |
hour = 6, | |
tzinfo = timezone.UTC() | |
) | |
print('{0} - {1}'.format(my_time,my_time.tzname())) | |
to_melbourne_time = my_time.astimezone(timezone.Melbourne()) | |
print('{0} - {1}'.format(to_melbourne_time,to_melbourne_time.tzname())) | |
if (__name__ == '__main__'): | |
main() |
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
2016-01-01 06:00:00+00:00 - UTC | |
2016-01-01 16:00:00+10:00 - Melbourne |
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
import datetime | |
class BaseTimezone(datetime.tzinfo): | |
TIMEDELTA_ZERO = datetime.timedelta(0) | |
def __init__(self,timezone_name,offset_seconds): | |
datetime.tzinfo.__init__(self) | |
self.timezone_name = timezone_name | |
self.offset = datetime.timedelta(seconds = offset_seconds) | |
def utcoffset(self,dt): | |
return self.offset | |
def dst(self,dt): | |
return BaseTimezone.TIMEDELTA_ZERO | |
def tzname(self,dt): | |
return self.timezone_name | |
# define timezones | |
class UTC(BaseTimezone): | |
def __init__(self): | |
BaseTimezone.__init__(self,'UTC',0) | |
class Melbourne(BaseTimezone): | |
def __init__(self): | |
BaseTimezone.__init__(self,'Melbourne',10 * 3600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment