Hello everyone I have a class that works with time, for example you enter two times and you can sum them (for now it doesn't matter that it goes beyond 23:59:59) or multiply them etc. The default input are zeros. There is also a function that returns current time. I can call time = Time()
which returns 0:00:00
, time = Time(12)
returns 12:00:00
.
The problem that I have is, I want to call time = Time('now')
and it should store there current time using function now()
, edits should be done in __init__()
(if you don't like now()
you can change it). But if i put time_now = ''
as first parameter it doesn't work, same when i put it as a last, because when I write time = Time('now')
it takes string 'now'
and wants to put it to hours.
I know there are time modules which can do this, but this is for learning purposes.
My code:
import random, time
class Time:
def __init__(self, hours=0, minutes=0, seconds=0, time_now=''):
# if time_now == 'now':
# now()
time = abs(3600*hours + 60*minutes + seconds)
self.hour = time//3600
self.min = time//60%60
self.sec = time%60
def __repr__(self):
return '{}:{:02}:{:02}'.format(self.hour,self.min,self.sec)
def __add__(self, other):
if isinstance(other, Time):
return Time(self.hour+other.hour, self.min+other.min, self.sec+other.sec)
if isinstance(other, int):
return Time(self.hour, self.min, self.sec+other)
__radd__ = __add__
def __sub__(self, other):
return Time(seconds = self.__int__() - other.__int__())
def __mul__(self, other):
return Time(self.hour*other.hour, self.min*other.min, self.sec*other.sec)
def __int__(self):
return 3600*self.hour + 60*self.min + self.sec
def __eq__(self, other):
return self.__int__() == other.__int__()
def __lt__(self, other):
return self.__int__() < other.__int__()
#writing out hour/min/sec what we want
def __getitem__(self, key):
if key == 0:
return self.hour
if key == 1:
return self.min
if key == 2:
return self.sec
#time now
def now():
a=(time.localtime()[3:6])
return Time(a[0],a[1],a[2])