我目前正在使用以下内容来计算两次差异。外出非常快,因此无论如何我都不需要显示仅为0.00的小时和分钟。我如何在Python中实际移位小数位?
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], "%.10f"%(float(in_ts) - float(out_ts)))
INFILE = 'C:/Users/kdalton/Documents/Minifile.txt'
print list(time_deltas(INFILE))
答案 0 :(得分:13)
与数学相同
a = 0.01;
a *= 10; // shifts decimal place right
a /= 10.; // shifts decimal place left
答案 1 :(得分:1)
或使用datetime模块
>>> import datetime
>>> a = datetime.datetime.strptime("30 Nov 11 0.00.00", "%d %b %y %H.%M.%S")
>>> b = datetime.datetime.strptime("2 Dec 11 0.00.00", "%d %b %y %H.%M.%S")
>>> a - b
datetime.timedelta(-2)
答案 2 :(得分:1)
def move_point(number, shift, base=10):
"""
>>> move_point(1,2)
100
>>> move_point(1,-2)
0.01
>>> move_point(1,2,2)
4
>>> move_point(1,-2,2)
0.25
"""
return number * base**shift
答案 3 :(得分:0)
扩大接受的答案;这是一个函数,它将给您提供的任何数字移动到小数位。如果小数位参数为0,则返回原始数字。为了一致性,总是返回float类型。
def moveDecimalPoint(num, decimal_places):
'''
Move the decimal place in a given number.
args:
num (int)(float) = The number in which you are modifying.
decimal_places (int) = The number of decimal places to move.
returns:
(float)
ex. moveDecimalPoint(11.05, -2) returns: 0.1105
'''
for _ in range(abs(decimal_places)):
if decimal_places>0:
num *= 10; #shifts decimal place right
else:
num /= 10.; #shifts decimal place left
return float(num)
print (moveDecimalPoint(11.05, -2))