简体   繁体   中英

How do I convert integers into high-resolution times in Python? Or how do I keep Python from dropping zeros?

Currently, I'm using this to calculate the time between two messages and listing the times if they are above 20 seconds.

def time_deltas(infile): 
    entries = (line.split() for line in open(INFILE, "r")) 
    ts = {}
    for e in entries:
        if " ".join(e[2:5]) == "OuchMsg out: [O]": 
            ts[e[8]] = e[0]    
        elif " ".join(e[2:5]) == "OuchMsg in: [A]":    
            in_ts, ref_id = e[0], e[7] 
            out_ts = ts.pop(ref_id, None) 
            yield (float(out_ts),ref_id[1:-1],(float(in_ts)*10000 - float(out_ts)*10000))

            n = (float(in_ts)*10000 - float(out_ts)*10000)
            if n> 20:
                print float(out_ts),ref_id[1:-1], n

    INFILE = 'C:/Users/klee/Documents/text.txt'
    import csv 

    with open('output_file1.csv', 'w') as f: 
    csv.writer(f).writerows(time_deltas(INFILE)) 

However, there are two major errors. First of all, python drops zeros when the time is before 10, ie. 0900. And, it drops zeros making the time difference not accurate.

It looks like: 130203.08766 when it should be: 130203.087660

You are yield ing floats, so the csv writer turns those floats into strings as it pleases.

If you want your output values to be a certain format, yield a string in that format.

Perhaps something like this?

print "%04.0f" % (900)     # prints 0900

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM