我试图使用Python在bash shell中打印出亚秒级的时间。
这在某种程度上与how-to-get-execution-time-of-a-script-effectively有关。我使用的是macos,bash在那里没有提供亚秒级的计时。
例如,如果我使用python -c 'from time import time; print(f"{time():.3f}")',我会得到:
1603052253.465python -c 'from time import time; print(f"{time():4.3f}")'具有相同的输出行为。
现在,这相当嘈杂。我真的不需要看到所有最左边的数字从一步到另一步的执行时间。
我写了一个新的脚本,做得更好:
$ time4bash.py
2325.987
$ time4bash.py
2328.201但是做这件事的代码比我预想的要复杂一些。
from time import time
time_ = time()
stime = f"{time_:.3f}"
#look for decimal separator, and this will break on `,` locales
pos = stime.index(".")
tstime = stime[pos-4:]
print(tstime)有没有更好的方式使用字符串格式标志或模数学?
发布于 2020-10-19 04:30:56
在用.3f格式化它之前,只需计算模数10,000的余数
>>> t = time.time()
>>> t
1603052957.262341
>>> t % 10000
2957.2623410224915
>>> '{:.3f}'.format(t % 10000)
'2957.262'或将所有内容放在一行中:
print('{:.3f}'.format(time.time() % 10000))发布于 2020-10-19 04:44:50
如果您只想将时间转换为小时、分钟、秒,您可以尝试这样的方法。
time.strftime("%H:%M:%S", time.gmtime())这将返回:
'20:42:13'您也可以使用以下命令获取本地时间:
time.strftime("%H:%M:%S", time.localtime())这将返回:
'13:47:54'https://stackoverflow.com/questions/64418008
复制相似问题