# Milliseconds with strftime

30855
2
08-22-2018 03:36 PM
MVP Esteemed Contributor

I need to return time to the millisecond;Python strftime reference  provides the %f format place holder, but when I use it in Python 3.x it fails.

This works:

from time import strftime
site = 'FP 20180822'
for i in range(1,10):
theTime = strftime("%H%M%S")
newTime = '{} {}'.format(site,theTime)
print('{}'.format(newTime))

#and returns:
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325
FP 20180822 162325

#the following fails with Invalid format String.
#Note the %f which allegedly provides milliseonds

from time import strftime
site = 'FP 20180822'
for i in range(1,10):
theTime = strftime("%H%M%S%f") #### %f
newTime = '{} {}'.format(site,theTime)
print('{}'.format(newTime))
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I was hoping that spinning it through a loop would get me down to the millisecond.  Any thoughts? (I can appended i at the end of new Time as a phony millisecond...)

That should just about do it....
1 Solution

Accepted Solutions
MVP Legendary Contributor
from datetime import datetime
curr_time = datetime.now()
formatted_time = curr_time.strftime('%H:%M:%S.%f')
print(formatted_time)

18:41:59.891075‍‍‍‍‍‍‍

.%f  dot... period

2 Replies
MVP Legendary Contributor
from datetime import datetime
curr_time = datetime.now()
formatted_time = curr_time.strftime('%H:%M:%S.%f')
print(formatted_time)

18:41:59.891075‍‍‍‍‍‍‍

.%f  dot... period

MVP Esteemed Contributor

No way to take out the colons and period without a split and join back together?

edited: just take them out:

from datetime import datetime
curr_time = datetime.now()
formatted_time = curr_time.strftime('%H%M%S%f')
print(formatted_time)

170342394082
That should just about do it....