simpler increment of time values?

Vlastimil Brom vlastimil.brom at
Thu Jul 5 15:18:09 CEST 2012

Many thanks to all for your suggestions!

Yes, the calculations with seconds since the Unix epoch is very
convenient for real times, but trying to make it dateless seemed to
make it more complicated for me.

The expected output for the increments asked by Jason was already
correctly stated by Devin; i.e.: 12:45 plus 12 hours is 0:45 and 12:45
minus 13 hours is 23:45.

Thanks for reminding me of dateutil.relativedelta, Mark, I didn't
think of it in this context (I always thought, the "relative" stands
for time and date calculations with regard to the current time and
date). There doesn't seem to be a way to use dateless time either
(unless I missed it),
however, it turns out, that one can probably work with this naive
"times" like with deltas (possibly ignoring other units than hours and
minutes in the result):

>>> td = dateutil.relativedelta.relativedelta(hours=9, minutes=45) + dateutil.relativedelta.relativedelta(minutes=30)
>>> "%s.%s" % (td.hours, td.minutes)
Which is probably the simplest and the most robust way, I found sofar.
It likely isn't the expected use case for relativedelta, but it seems
to work ok. (Are there maybe some drawbacks I am missing?)
(Well I just found one possible pitfall , if floats are passed:
>>> td = dateutil.relativedelta.relativedelta(hours=9, minutes=45) + dateutil.relativedelta.relativedelta(minutes=30.5)
>>> "%s.%s" % (td.hours, td.minutes)
, but its beyond my current use case, and the validation can always be added.)

The same would be doable using the built in timedelta too, but there
are no hours and minutes in its output, hence these are to be
converted from the seconds count.

>>> dttd=datetime.timedelta(hours=9, minutes=45) + datetime.timedelta(minutes=30)
>>> dttd
datetime.timedelta(0, 36900)
>>> dttd.seconds
>>> s = dttd.seconds
>>> h,s = divmod(s,3600)
>>> m,s = divmod(s,60)
>>> h,m,s
(10, 15, 0)
>>> "%s.%s" % (h, m)

Any thoughts?
 thanks again,


More information about the Python-list mailing list