[Tutor] Time script help sought!

Liam Clarke cyresse at gmail.com
Wed Jan 12 23:48:03 CET 2005


I'm real sorry. 

My standard disclaimer is now amended to include - "Never post untested code"

Disregard everything I wrote above. I feel real bad, so bad that I did
something I very rarely do... write complete code.

See attached txt file. Guaranteed to work, if you still want to turn 

Item_4 DAT 5 12:32:05 12:37:13 Funny crackling noise

into Item_4 DAT 5 00:00:00 00:05:08 Funny crackling noise

Please note comment can be included. Not overly hard.

HTH, 

(And sorry for erroneous datetime stuff. Particularly
datetime.datetime(timedelta object)
That definitely doesn't work.)

Never post untested code

Liam Clarke

On Wed, 12 Jan 2005 10:08:02 -0500, kevin parks <kp8 at mac.com> wrote:
> thanks everyone... I will look at all the various appraoches folks came
> up with and see what i can learnn from them. I ended doing something
> lame -- a brute force method. I formmatted and reformatted my input
> data and stuffed it in a HUGE dictionary.... it was stupid and
> kludgy.... i hope to study all these approaches and learn something
> that may help me do something that is more flexible about the input
> data and is more elegant..... here's what i
> came up with ... with my pea sized brain...
> 
> #!/usr/bin/env python
> 
> # New in version 2.3 is the 'datetime' module (see standard library
> reference)
> # http://www.python.org/doc/lib/module-datetime.html
> 
> import datetime
> 
> inseqs = { (1) : ['DAT_1', '01', '00:00:23', '00:08:23'],
> (2) : ['DAT_1', '02', '00:08:23', '00:09:41'],
> (513) : ['DAT_75', '10', '00:59:55', '01:11:05'],
> (514) : ['DAT_75', '11', '01:11:05', '01:16:15'],
> (515) : ['DAT_75', '12', '01:16:15', '01:34:15'],
> (516) : ['DAT_75', '13', '01:34:15', '01:45:15'],
> (517) : ['DAT_75', '14', '01:45:15', '01:48:00'] }
> 
> mykeys = inseqs.keys()      # first make a copy of the keys
> mykeys.sort()               # now sort that copy in place
> 
> for key in mykeys:
>      event = inseqs[key]
>      print '\n','Item #', key, event
>      TD = datetime.timedelta
>      h, m, s = event[2].split(':')
>      zero_adjust = TD(hours=int(h), minutes=int(m),seconds=int(s))
>      #
>      print ' Q___ ', key, event[:2], ': ',
>      for item in event[2:]:
>          hrs, mins, secs, = item.split(':')
>          time1 = TD(hours=int(hrs), minutes=int(mins),seconds=int(secs))
>          print time1 - zero_adjust,
> 
>      print
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
-------------- next part --------------
# By Liam Clarke
# A wee bitty of text processing code.
# Written in apology for some very wrong info I gave about using datetime objects.
# Golden rule - never post untested code. 
#
#     Caveats
#
# This code will always be expecting input like - 
# item_1, DAT, 3, 00:00:00, 12:32:00<, optional comment> 
# Data should be separated by a comma and a space
# Of course, you can just change the constant sep to whatever you want.
#
# While the value of the first 3 values doesn't matter
# The fourth and fifth have to be start and finish
# and the two time values must be in format HH:MM:SS, 24 hour.
#
# IMPORTANT - This was written in Notepad (!), so the TABS are all funky.
# If you want to copy and paste, detabbify and then retab using proper 4 space tabs.
# (And of course, change inpFile and outpFile to appropriate names.)
# Python likes forward slashes in paths, they work on all systems.


 




import datetime

# init - inpFile is the data to be processed, sep is what separates the values on each line,
# in this case a comma followed by a space. 
# I've read from the file using readlines() instead of read(). This gives a list, each line
# being a separate list item. Which makes it easy to step through.



def parseTime(timeStr):
        # I love split and a lot of the other string methods
	splitTime=timeStr.split(":")
	return splitTime


inpFile = "dump.txt"
outpFile = "redumped.txt"
sep = ", "


openFile = file(inpFile, "r")
listOfLines = openFile.readlines()
openFile.close()
newTimes = []


for line in listOfLines:
	#Remove superfluous newlines
	if line.endswith("\n"):
		line=line.rstrip("\n")
	
	#So "a, b, c, d, e" will become ['a', 'b', 'c', 'd', 'e']
	splitLine = line.split(sep)
	
	#Just assign friendlier names 
	(item, dat, num, start, finish) = ( splitLine[0], splitLine[1],
				            splitLine[2], splitLine[3], 
				            splitLine[4] )

	if len(splitLine)=5:
		#Comments are optional, 
                #so if line splits into 6 elements, 
                # there's a comment, so grab it.
		comment=splitLine[5] 
	else:
		#As I'll be boolean testing for a comment, it needs a value 
		comment=None

	
	splitStart = parseTime(start)
	splitFinish = parseTime(finish)

	
	#Just a wee explanation about datetime 
        #
        # Datetime.time objects are easier - but....
        # They don't support time arithmetic.
        # Hence the use of datetime.datetime objects.
        #
        # datetime objects are initialised like so - 
        # datetime.datetime(year, month, day, hour, minute, second)
        # Hour is 24 hour. All values must be integers
        # And day and month cannot be 01 or similar, they must be 1.
     
	startDateObj = datetime.datetime(1901, 1, 1, 
				     int(splitStart[0]),
				     int(splitStart[1]),
				     int(splitStart[2]) )

	finishDateObj = datetime.datetime(1901, 1, 1, 
				      int(splitFinish[0]),
				      int(splitFinish[1]),
				      int(splitFinish[2]) )
	
        # Arithmetic on datetime objects returns a timedelta object.
	# Unfortunately, a timedelta object doesn't have the strftime method
        # so a new datetime object is needed.

	diffDeltaObj = finishDateObj - startDateObj
	deltaStr = str(diffDeltaObj)
	splitDelta = parseTime(deltaStr)

	deltaObj = datetime.datetime(1901, 1, 1,
				     int(splitDelta[0]), 
				     int(splitDelta[1]),
				     int(splitDelta[2])
                                     )
	
	#So, now we've got a datetime object equivalent to the time difference
        #between start and finish, so output it as HH:MM:SS
	
	endTime = deltaObj.strftime("%H:%M:%S")
        
        #Now chuck all back together like we found it, just with changed times
	lineToWrite = item + sep +dat + sep + num + sep + "00:00:00" + sep + endTime
	
	if comment:
		#If there is a comment, add it too.
		lineToWrite += sep + comment

	lineToWrite += '\n' #Just add a newline to keep it organised.
	
	newTimes.append(lineToWrite) #Append finished line to list to write when done


saveFile = file(outpFile, "w")

for item in newTimes:
	saveFile.write(item)

saveFile.close()
	


More information about the Tutor mailing list