简体   繁体   中英

Preventing rounding to 2 decimal places

I have been working on some code for quite a few days now and to be honest, I haven't got much hair left... I have searched everywhere including stackoverflow and I can't seem to anything matching my predicament.

I am using python 2.7.6 on Mint 17.3. I need to work with date/time to at least millisecond precision. Working with date and time in whole seconds is fairly trivial but when you throw in milli or microseconds it becomes a completely different ballgame. Ultimately, I need to iterate through a log file and based upon certain conditions, I will need to find the difference between date/times of two lines to at least millisecond precision. The precision really does matter where a server, PLC's and scanners are involved in this warehouse conveyor situation. The log file date/time is formatted like this:

12-Apr-2016 23:59:59.720321

I thought the easiest way to deal with this was to convert the string into a timestamp and then add the microseconds afterwards. I am also not too sure of my use of strptime in this context as I know that timetuple() strips any fraction anyway, thus is surplus to requirements.

Anyway, after many, many tries, and days my code for this so far is below:

def timestampthen(timestring):
    tt = datetime.datetime.strptime(timestring, "%d-%b-%Y %H:%M:%S.%f").timetuple()
    ut = float(calendar.timegm(tt))
    dotpos = timestring.rfind(".")
    frac = float(timestring[dotpos:])
    utfloat = float(ut + frac)
    return utfloat

In an example, ut = 1460505599.0 and frac = 0.720321, yet utfloat = 1460505599.72

I know I can use format and %f but I am working with floats and not strings. The above code works fine but why does the float come back with a 2 decimal point precision when it is 6 or more? I need more. I would appreciate some guidance to point me in the right direction, please.

The full precision is actually present, so there is no problem with the arithmetic.

The problem is that by default, print displays the rounded str of the variable instead of its full precision repr :

>>> ut = 1460505599.0; frac = 0.720321;
>>> ufloat = ut + frac
>>> print str(ufloat)
1460505599.72
>>> print repr(ufloat)
1460505599.720321

So, the solution to your problem is just to print the repr of the float value so it will display to full precision. Hope this helps :-)

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