python time arithmetic with datetime?

Status
You're currently viewing only elipsey's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

elipsey

Wise, Aged Ars Veteran
179
so i want a date/time class that does math on times so i don't have to. like this:

t1 = mytimeclass.time(10, 15)
t2 = mytimeclass.time(4, 20)
t3 = t2 - t1

...or something.

but the python datetime.time class doesn't seem to have defined arithmetic operators, nor does the datetime.timedelta. if there are methods for this, that's not obvious to me either:

Code:
>>> t1 = datetime.time(12,20)
>>> t1
datetime.time(12, 20)
>>> t1.hour
12
>>> t1.minute
20
>>> t2 = datetime.time(12,30)
>>> t1 - t2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
>>> td = datetime.timedelta(t1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported type for timedelta days component: datetime.time
>>> td = datetime.timedelta(t1,t2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported type for timedelta seconds component: datetime.time
>>>
>>> td = datetime.timedelta(15)
>>> t3 = t1 - td
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.timedelta'
>>> print 'sheesh'

of course this is easy enough to write:
Code:
# t_end, t_start are 'HHMM'
if int(t_end[0]) > int(t_start[0]):
    duration = ((int(t_end[0])-int(t_start[0]))*60)+(int(t_end[2])-int(t_start[2]))
else: # if midnight roll-over occurs, hours elapsed is t_end + 24 - t_start 
    duration = ((int(t_end[0])+(24-int(t_start[0])))*60)+(int(t_end[2])-int(t_start[2]))

...but i do stuff like this all the time, and i would rather avoid code duplication, and stupid mistakes.

if i want to do math on times, do i have to write it myself? what is the point of having a datetime class in that case? just input validation? abstraction of dates for different timezones? (i think the docs say you only get that if you write the timezone info yourself in a subclass) if i wanted to write this stuff my self, why would i use datetime???

what am i missing here?
 

elipsey

Wise, Aged Ars Veteran
179
thx guys, perfect answers.

Code:
>>> t1 = mx.DateTime.Time(1,2)
>>> t1
<mx.DateTime.DateTimeDelta object for '01:02:00.00' at 7f6bc772bf80>
>>> t2 = mx.DateTime.Time(1,3)
>>> t2
<mx.DateTime.DateTimeDelta object for '01:03:00.00' at 7f6bc76d8180>
>>> t3 = t2 - t1
>>> t3
<mx.DateTime.DateTimeDelta object for '00:01:00.00' at 7f6bc76d8b58>

mmmmmm... that's good datetime
 
Status
You're currently viewing only elipsey's posts. Click here to go back to viewing the entire thread.
Not open for further replies.