473,387 Members | 1,603 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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

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
p.s.
In case this looks like I'm asking for a homework exercise, here's what
I'm using now. It returns False or raises a ValueError exception for
invalid inputs. I'm just wondering if there's an already-published
version.
def dms2int(dms):
"""Accepts an 8-character string of three two-digit numbers,
separated by exactly one non-numeric character, and converts it
to an integer, representing the number of seconds. Think of
degree, minute, second notation, or time marked in hours,
minutes, and seconds (HH:MM:SS)."""
return (
len(dms) == 8
and 00 <= int(dms[0:2]) < 24
and dms[2] not in '0123456789'
and 00 <= int(dms[3:5]) < 60
and dms[5] not in '0123456789'
and 00 <= int(dms[6:8]) < 60
and int(dms[6:8]) + 60 * (int(dms[3:5]) + 60 * int(dms[0:2]))
)

Jul 27 '06 #1
6 6996
go*****@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
p.s.
In case this looks like I'm asking for a homework exercise, here's what
I'm using now. It returns False or raises a ValueError exception for
invalid inputs. I'm just wondering if there's an already-published
version.
def dms2int(dms):
"""Accepts an 8-character string of three two-digit numbers,
separated by exactly one non-numeric character, and converts it
to an integer, representing the number of seconds. Think of
degree, minute, second notation, or time marked in hours,
minutes, and seconds (HH:MM:SS)."""
return (
len(dms) == 8
and 00 <= int(dms[0:2]) < 24
and dms[2] not in '0123456789'
and 00 <= int(dms[3:5]) < 60
and dms[5] not in '0123456789'
and 00 <= int(dms[6:8]) < 60
and int(dms[6:8]) + 60 * (int(dms[3:5]) + 60 * int(dms[0:2]))
)
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

Jul 27 '06 #2
On Wed, 2006-07-26 at 20:18 -0700, John Machin wrote:
go*****@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
p.s.
In case this looks like I'm asking for a homework exercise, here's what
I'm using now. It returns False or raises a ValueError exception for
invalid inputs. I'm just wondering if there's an already-published
version.
def dms2int(dms):
"""Accepts an 8-character string of three two-digit numbers,
separated by exactly one non-numeric character, and converts it
to an integer, representing the number of seconds. Think of
degree, minute, second notation, or time marked in hours,
minutes, and seconds (HH:MM:SS)."""
return (
len(dms) == 8
and 00 <= int(dms[0:2]) < 24
and dms[2] not in '0123456789'
and 00 <= int(dms[3:5]) < 60
and dms[5] not in '0123456789'
and 00 <= int(dms[6:8]) < 60
and int(dms[6:8]) + 60 * (int(dms[3:5]) + 60 * int(dms[0:2]))
)

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

You may also want to look at the dateutil module (especially dateutil.parse).


--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

Jul 27 '06 #3
In <11**********************@b28g2000cwb.googlegroups .com>, John Machin
wrote:
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.
Looking at the subject I would expect to be able to give 76°04'54" as
argument. Hm, but degrees don't map directly to hours!?

Ciao,
Marc 'BlackJack' Rintsch
Jul 27 '06 #4
John Machin wrote:
go*****@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

Jul 27 '06 #5

go*****@lazytwinacres.net wrote:
John Machin wrote:
go*****@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.
The bigger pain would have been two types of error handling
(try/except) *AND* if result is False
>
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.
That's a bit too elaborate. Python gives you the hard-coded date for
free -- then (you ingrate!) you ignore it, like this:

|>import time
|>dms = "23:48:59"
|>t = time.strptime(dms, "%H:%M:%S")
|>t
(1900, 1, 1, 23, 48, 59, 0, 1, -1)
|>seconds = (t[3] * 60 + t[4]) * 60.0 + t[5]
|>seconds
85739.0 # assuming you do want it as a float, not an int

Cheers,
John

Jul 27 '06 #6
<go*****@lazytwinacres.netwrote in message
news:11********************@h48g2000cwc.googlegrou ps.com...
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
In a froth of functionalism, here is my submission.

-- Paul
tests = """\
00:00:00
01:01:01
23:59:59
24:00:00
H1:00:00
12:34:56.789""".split("\n")

def time2secs(t,decimal=False):
if decimal:
tflds = map(float,t.split(":"))
else:
tflds = map(int,t.split(".")[0].split(":"))
nomorethan = lambda (a,maxa) : 0 <= a < maxa
if sum(map(nomorethan, zip(tflds,(24,60,60)))) == len(tflds):
return reduce(lambda a,b: a*60+b, tflds)
else:
raise ValueError("invalid time field value in '%s'" % str(t))

for tt in tests:
try:
print time2secs(tt)
print time2secs(tt,True)
except Exception,e:
print "%s: %s" % (e.__class__.__name__, e)
Jul 27 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Ken | last post by:
hello, I would to know if it is possible to call an object in a function within a class. Meaning , In a class, A function X calling onto a function Y, and function Y we want one of the two...
3
by: fred14214 | last post by:
I need to be able to enter an elapsed time into a text field. This time then needs to be converted into seconds and stored in a field in some table. The user will enter a time (format is...
2
by: James P. | last post by:
Hello, In my Access report, I have a minutes field in the detail line. How do I convert that minute to hour and minute. The problem for me now is if I take the minutes, say 75 divide by 60, it...
6
by: Penguin | last post by:
At some long ago time Steve Jorgensen answered thus: Subject: Re: How can I round a time? Newsgroups: comp.databases.ms-access Date: 1998/12/11 Access represents a date internally as a double...
11
by: Bore Biko | last post by:
Dear, I have function that transform time from secconds to string formated as dd:hh:mm:ss (days:hours:minutes:seconds), but it doesent work correctly... Here s code compiled with gcc it goes...
1
by: DaveF | last post by:
I need to do some calculations with lat long. Does anyone have an example how to work with lat long so I don't loose values -- David
11
by: simon | last post by:
I have the name of a day like for example 'Mon' Is there some function which returns the number of a weekDay if you have the day name or I should write the select case statements? If the day is...
3
by: Laguna | last post by:
Hi, I have an XML file in a single long string. How can I convert it into the nicely indented format as displayed by Internet Explorer using Python? Thanks, Laguna Input XML file (one...
2
by: dwasbig9 | last post by:
Hi Group (fairly limited knowledge of Access and almost none of Access VBA. Using Access 2003). I need to sum time, I've found through the groups archive an sql extract that led me to this ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.