function to convert degree (hour), minute, seconds string to integer

google0 at lazytwinacres.net google0 at lazytwinacres.net
Thu Jul 27 06:34:52 EDT 2006


John Machin wrote:
> google0 at lazytwinacres.net wrote:
> > I know this is a trivial function, and I've now spent more time
> > searching for a surely-already-reinvented wheel than it would take to
> > reinvent it again, but just in case... is there a published,
> > open-source, function out there that takes a string in the form of
> > "hh:mm:ss" (where hh is 00-23, mm is 00-59, and ss is 00-59) and
> > converts it to an integer (ss + 60 * (mm + 60 * hh))?  I'd like
> > something that throws an exception if hh, mm, or ss is out of range, or
> > perhaps does something "reasonable" (like convert "01:99" to 159).
> > Thanks,
> >     --dang
>
> Have you considered time.strptime()?
>
> BTW, your function, given "00:00:00" will return 0 -- you may well have
> trouble distinguishing that from False (note that False == 0), without
> resorting to ugliness like:
>
>     if result is False ...
>
> Instead of returning False for some errors and letting int() raise an
> exception for others, I would suggest raising ValueError yourself for
> *all* invalid input.
>
> You may wish to put more restrictions on the separators ... I would be
> suspicious of cases where dms[2] != dms[5]. What plausible separators
> are there besides ":"? Why allow alphabetics? If there's a use case for
> "23h59m59s", that would have to be handled separately. Note that
> "06-12-31" could be a date, "12,34,56" could be CSV data.
>
> Cheers,
> John

Good point about 0/False.  I don't think it would have bitten me in my
current program, given my expected (and filtered) inputs, but I might
have reused it in the future, and been bitten later.

I had looked at the time module, but apparently not long enough.
This does the trick:

def dms2int(dms):
    int(time.mktime(time.strptime("2000-01-01 %s" % dms, "%Y-%m-%d
%H:%M:%S")))

I only need the minutes, but can work with seconds.  The only downside
is that I'm hardcoding an arbitrary date, but I can deal with that.

Thanks for your help, John!
    --dang




More information about the Python-list mailing list