calculating the length of something in python

Filed under:Uncategorized — posted by admin on September 14, 2011 @ 11:11 am

i wrote this python script at work a while ago (basically out of boredom, as you might see by my code, i’m not a programmer). and then i changed it around a bunch as i learned more python. basically, i catalog things and sometimes have to find out the length of them. before this, i would have to do it in my head, going from the start time within a bigger file (that would generally be somewhere between half-an-hour and an hour long). and sometimes it’s easy enough to do that in my head, and sometimes i feel a little fried, so this makes the job easier.


import datetime, re

def main():
    start()
    end()
    calculate()
# the start function gets the end time, uses a regular expression to check if the input has been done as instructed, and then slices out the numbers from XX:XX
def start():
    global StartMin, StartSec
    Start = raw_input("start time ('MM:SS'): ")
    match = re.match('(^\d\d:\d\d$)', Start)
    if match is not None:
        StartMin = int(Start[0:2])
        StartSec = int(Start[3:5])
	end()
    else:
        print "enter in format 'MM:SS'"
        start()
# the end function gets the end time, uses a regular expression to check if the input has been done as instructed, and then slices out the numbers from XX:XX
def end():
    global EndMin, EndSec
    End = raw_input("end time ('MM:SS'): ")
    match = re.match('(^\d\d:\d\d$)', End)
    if match is not None:
	EndMin = int(End[0:2])
        EndSec = int(End[3:5])
        calculate()
    else:
        print "enter in format 'MM:SS'"
        end()
# the calculate function calculates the length by converting both the start and end times into seconds, subtracting the total of seconds from the beginning, and then converting the remaining seconds, which is the actual length, into a time value using the timedelta function from the datetime module
def calculate():
    global StartMin, EndMin, StartSec, EndSec
    secstar = (StartMin*60) + StartSec
    secend = (EndMin*60) + EndSec
    sectot = secend - secstar
    print datetime.timedelta(seconds=sectot)
    start()
while True:
    main()

zero comments so far

Please won't you leave a comment, below? It'll put some text here!

Copy link for RSS feed for comments on this post

Sorry, the comment form is closed at this time.



image: detail of installation by Bronwyn Lace