XYZ
XYZ

Reputation: 162

How to get the time to milliseconds resolution python

I want to get the time in milli seconds resolution not microsecondsso basically my code is

now = datetime.now()
now.strftime("%Y-%m-%d-%H:%M:%S.%f")

But that write it to micro I want just to keep the first 3 digits of the microseconds so some kinda like %3f but ofcourse that is not correct

Upvotes: 2

Views: 1542

Answers (2)

Dima Tisnek
Dima Tisnek

Reputation: 11779

Subsecond resolution without full seconds:

time.time() % 1
0.3413050174713135

Or if you insist on milliseconds alone, then:

round(time.time() * 1000) % 1000
228.0

Add an int(...) if you don't like empty fractional part :)

Upvotes: 0

Maltysen
Maltysen

Reputation: 1946

Very simple:

now.strftime("%Y-%m-%d-%H:%M:%S.%f")[:-3]

This just slices the string to get rid of the last three characters of it.

Upvotes: 2

Related Questions