formatted 'time' data in calculations

John Machin sjmachin at lexicon.net
Wed Jan 7 16:14:17 EST 2009


On Jan 8, 6:23 am, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
> Ross wrote:
> > There seems to be no shortage of information around on how to use the
> > time module, for example to use time.ctime() and push it into strftime
> > and get something nice out the other side, but I haven't found anything
> > helpful in going the other way.
>
> As to a paucity of conversion formatting, there is no magic way to take
> everyone's way of putting date and time information in text and convert
> it to unambiguous format, in part because there are too many different
> and contradictory formats.  When I write dates, I know what I intended;
> when I read dates, I guess what the author intended.
>
> Have you read the entire time module document?  If so, which functions
> in that module take strings as arguments?
>
> > That is, given some formatted text describing times - is there something
> > that makes it easy to calculate time differences, or do I have to index
> > my way through the string pulling out characters, converting to integers
> > etc...
>
> > Data is formatted:
> >    t1 = 09:12:10
> >    t2 = 11:22:14
> > I want to calculate tdiff = t2-t1
>
> Do you do any work yourself?  Show us your attempts.  This looks like
> a trivial exercise.  It seems that for less than four times the effort
> of asking your question you might have found the answer.
>
> Perhaps I am being too cranky this morning.

Indeed. Be not cranky at clueless bludgers and cargo-cultists lest
they rise high in the serried ranks of IT management and remember your
name inclusive-or the net-nannies sally forth and wallop thee with a
balloon on a stick.

To the OP: Your Lordship did not specify whether output should be
expressed in hours and a fraction, or in hours, minutes, and seconds.
So that the eminent one may avoid having to make a decision in public,
I humbly submit answers to both possibilities:

>>> t1 = "09:12:10"
>>> t2 = "11:22:14"
>>> sum((a - b) / c for (a, b, c) in zip(map(int, t2.split(":")), map(int,t1.split(":")), (1., 60., 3600.)))
2.1677777777777778
>>> def tdiff(t1, t2):
...    h, m, s = [a - b for (a, b) in zip(map(int, t2.split(":")), map
(int,t1.split(":")))]
...    if s < 0:
...       s += 60
...       m -= 1
...    if m < 0:
...       m += 60
...       h -= 1
...    return h, m, s
...
>>> tdiff(t1, t2)
(2, 10, 4)
>>> tdiff('09:12:10', '10:11:09')
(0, 58, 59)

HTH,
John




More information about the Python-list mailing list