Created
October 21, 2015 14:01
-
-
Save hallazzang/e5c050ef5e1ad60dec79 to your computer and use it in GitHub Desktop.
Tricky time representation in Python
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
class SliceTime(object): | |
@property | |
def hour(self): | |
return self._hour | |
@hour.setter | |
def hour(self, value): | |
if not isinstance(value, (int, long)) or not 0 <= value <= 23: | |
raise ValueError('hour must be an integer value in 0 ~ 23') | |
else: | |
self._hour = value | |
@property | |
def min(self): | |
return self._min | |
@min.setter | |
def min(self, value): | |
if not isinstance(value, (int, long)) or not 0 <= value <= 59: | |
raise ValueError('min must be an integer value in 0 ~ 59') | |
else: | |
self._min = value | |
@property | |
def sec(self): | |
return self._sec | |
@sec.setter | |
def sec(self, value): | |
if not isinstance(value, (int, long)) or not 0 <= value <= 59: | |
raise ValueError('sec must be an integer value in 0 ~ 59') | |
else: | |
self._sec = value | |
def __repr__(self): | |
return '<SliceTime {0.hour:02}:{0.min:02}:{0.sec:02}>'.format(self) | |
def __getitem__(self, arg): | |
if isinstance(arg, slice) and arg.start != None and arg.stop != None: | |
self.hour = arg.start | |
self.min = arg.stop | |
self.sec = arg.step or 0 | |
elif isinstance(arg, (int, long)): | |
self.hour = arg | |
self.min = 0 | |
self.sec = 0 | |
else: | |
raise Exception('invalid time format') | |
return self | |
Time = SliceTime() | |
if __name__ == '__main__': | |
print Time[12] # <SliceTime 12:00:00> | |
print Time[15:30] # <SliceTime 15:30:00> | |
print Time[5:45:20] # <SliceTime 05:45:20> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment