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

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


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 datetimedatetime.now().strftime("%H:%M:%S.%f")

Should do the trick!


You are looking at the wrong documentation. The time module has different documentation.

You can use the datetime module strftime like this:

>>> from datetime import datetime>>>>>> now = datetime.now()>>> now.strftime("%H:%M:%S.%f")'12:19:40.948000'


With Python's time module you can't get microseconds with %f.

For those who still want to go with time module only, here is a workaround:

now = time.time()mlsec = repr(now).split('.')[1][:3]print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))

You should get something like 2017-01-16 16:42:34.625 EET (yes, I use milliseconds as it's fairly enough).

To break the code into details, paste the below code into a Python console:

import time# Get current timestampnow = time.time()# Debug nownowprint nowtype(now)# Debug strf timestruct_now = time.localtime(now)print struct_nowtype(struct_now)# Print nicely formatted dateprint time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)# Get milisecondsmlsec = repr(now).split('.')[1][:3]print mlsec# Get your required timestamp stringtimestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)print timestamp

For clarification purposes, I also paste my Python 2.7.12 result here:

>>> import time>>> # get current timestamp... now = time.time()>>> # debug now... now1484578293.519106>>> print now1484578293.52>>> type(now)<type 'float'>>>> # debug strf time... struct_now = time.localtime(now)>>> print struct_nowtime.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)>>> type(struct_now)<type 'time.struct_time'>>>> # print nicely formatted date... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)2017-01-16 16:51:33 EET>>> # get miliseconds... mlsec = repr(now).split('.')[1][:3]>>> print mlsec519>>> # get your required timestamp string... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)>>> print timestamp2017-01-16 16:51:33.519 EET>>>