Reputation: 12154
I was trying to print out sub-seconds timing in a bash shell, using Python.
This is somewhat related to how-to-get-execution-time-of-a-script-effectively. I'm on macos and bash provides no subsecond timings there.
If I use python -c 'from time import time; print(f"{time():.3f}")'
for example I get:
1603052253.465
python -c 'from time import time; print(f"{time():4.3f}")'
has the same output behavior.
Now, this quite noisy. I don't really need to see all the leftmost digits to eyeball execution time from step to step.
I wrote a new script that does it much more nicely:
$ time4bash.py
2325.987
$ time4bash.py
2328.201
But the code to do it was somewhat more involved than I would have preferred.
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)
Is there a better way using either string format flags or modulo math?
Upvotes: 1
Views: 185
Reputation: 8508
If you want to convert time to hour, min, secs only, you can try something like this.
time.strftime("%H:%M:%S", time.gmtime())
This will return:
'20:42:13'
You can also get local time using:
time.strftime("%H:%M:%S", time.localtime())
This will return:
'13:47:54'
Upvotes: -1
Reputation: 155363
Just compute the remainder modulo 10,000 before formatting it with .3f
:
>>> t = time.time()
>>> t
1603052957.262341
>>> t % 10000
2957.2623410224915
>>> '{:.3f}'.format(t % 10000)
'2957.262'
or put all together in one line:
print('{:.3f}'.format(time.time() % 10000))
Upvotes: 3