Skip to content

Instantly share code, notes, and snippets.

@schlarpc
Created October 3, 2017 23:41
Show Gist options
  • Save schlarpc/f45761388162b2886dec42bd1879e44a to your computer and use it in GitHub Desktop.
Save schlarpc/f45761388162b2886dec42bd1879e44a to your computer and use it in GitHub Desktop.
slice-based time
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