Created
October 3, 2017 23:41
-
-
Save schlarpc/f45761388162b2886dec42bd1879e44a to your computer and use it in GitHub Desktop.
slice-based time
This file contains 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 GetTime(type): | |
def __getitem__(cls, item): | |
if isinstance(item, slice): | |
hours = item.stop if item.start is None else item.start | |
minutes = item.stop if item.start is not None else 0 | |
seconds = item.step or 0 | |
elif isinstance(item, int): | |
hours = item | |
minutes = 0 | |
seconds = 0 | |
else: | |
raise ValueError() | |
return datetime.datetime.now().replace(hour=hours, minute=minutes, second=seconds, microsecond=0) | |
class Time(metaclass=GetTime): | |
pass | |
print(Time[5]) | |
print(Time[7:00]) | |
print(Time[0:30]) | |
print(Time[18:21:58]) | |
# Outputs: | |
# 2017-10-03 05:00:00 | |
# 2017-10-03 07:00:00 | |
# 2017-10-03 00:30:00 | |
# 2017-10-03 18:21:58 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment