How do I change the format/amount of digits that a

2019-09-08 08:51发布

I'm very new to Python and have a question. Currently I'm using this to calculate the times between a message goes out and the message comes in. The resulting starting time, time delta, and the Unique ID are then presented in file. As well, I'm using Python 2.7.2

Currently it is subtracting the two times and the result is 0.002677777777(the 0.00 are hours and minutes) which I don't need. How do I format it so that it would start with seconds (59.178533,00) with 59 being seconds. As well, sometimes python will display the number as 8.9999999 x e-05. How can I force it to always display the exact number.

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) - float(out_ts))

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

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

Here's a small sample of the data:

61336.206267 - OuchMsg out: [O] enter order. RefID [F25Q282588] OrdID [X1F3500687  ]

标签: python digit
2条回答
不美不萌又怎样
2楼-- · 2019-09-08 09:06

If float(out_ts) are hours, then '{0:.3f}'.format(float(out_ts) * 3600.) will give you the text representation of seconds with three digits after decimal point.

查看更多
SAY GOODBYE
3楼-- · 2019-09-08 09:15

How can I force it to always display the exact number.

This is sometimes not possible, because of floating point inaccuracies

What you can do on the other hand is to format your floats as you wish. See here for instructions.

E.G: replace your yield line with:

yield ("%.5f"%float(out_ts),"%.5f"%ref_id[1:-1], "%.5f"%(float(in_ts) - float(out_ts)))

to truncate all your values to 5 digits after the comma. There are other formatting options, for a lot of different formats.

查看更多
登录 后发表回答