Fix Python – Using %f with strftime() in Python to get microseconds

Question

Asked By – oakbramble

I’m trying to use strftime() to microsecond precision, which seems possible using %f (as stated here). However when I try the following code:

import time
import strftime from time

print strftime("%H:%M:%S.%f")

…I get the hour, the minutes and the seconds, but %f prints as %f, with no sign of the microseconds. I’m running Python 2.6.5 on Ubuntu, so it should be fine and %f should be supported (it’s supported for 2.6 and above, as far as I know.)

Now we will see solution for issue: Using %f with strftime() in Python to get microseconds


Answer

You can use datetime’s strftime function to get this. The problem is that time’s strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!

This question is answered By – adamnfish

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0