[Newbie] Need help with quick text proggy.

Jeff Davis jdavis at empires.org
Thu Oct 10 07:12:24 CEST 2002


Here is one approach:

-----begin convertfile.py--------
import re

def convert_time(time):
        hours = re.sub(r'(\d\d?):(\d\d)(a|p)',r'\g<1>',time)
        minutes = re.sub(r'(\d\d?):(\d\d)(a|p)',r'\g<2>',time)
        ampm = re.sub(r'(\d\d?):(\d\d)(a|p)',r'\g<3>',time)
        hours = int(hours) + 6 # this adds the time you needed
        if hours == 12:
                hours = 0
        if ampm == 'p':
                hours += 12
                ampm = 'a'
        if hours >= 24:
                hours -= 24
        if hours > 12:
                hours -=12
                ampm = 'p'
        if hours == 0:
                hours = 12
        return "%s:%s%s" % (hours,minutes,ampm)

input = open('input.file','r')
output = open('output.file','w')

line = input.readline()
while line:
        (time,number) = line.split()
        time = convert_time(time)
        output.write("%s        %s\n" % (time,number))
        line = input.readline()

input.close()
output.close()
--------end convertfile.py---------------

I'll leave the initial debugging to you. If you have any more questions, 
just ask. I hope I understood your problem correctly.

Oh, and it could probably be solved more eloquently than I have done. I 
always have difficuly translating dates all around. As far as I can tell, 
12 acts kind of like 0, since 12pm is noon and 12am is midnight (right?). 
Anyway, hope it helps.

Regards,
        Jeff


Corey Woodworth wrote:

> I havn't programmed in python in a while (not since 2.0) but I just
> found myself in a predicament where I really need to write a program
> and write it fast. Python still seems to be the best choice even
> though I'm very rusty and wasn't to good to start with. Here is my
> problem. I've got a text file that is a list of elements. a time
> followed by a number on each line. Like this for example:
> 
> 1:46p 65
> 5:45a 99
> 2:36p 88
> 10:53a        79
> 5:10a 86
> 2:43p 169
> 10:14a        55
> 
> I just found out that all my times are 6 hours off. (AARGH!) and I
> need some help writing a program that will update all those timestamps
> for me. Any help at all is appreciated, wheter it be links, some
> source, or whatever. Thank a bunch.
> 
> Corey




More information about the Python-list mailing list