Milliseconds with strftime

22065
2
Jump to solution
08-22-2018 03:36 PM
JoeBorgione
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....
0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Esteemed 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‍‍‍‍‍‍‍

How to get min, seconds and milliseconds from datetime.now() in Python 

.%f  dot... period

View solution in original post

2 Replies
DanPatterson_Retired
MVP Esteemed 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‍‍‍‍‍‍‍

How to get min, seconds and milliseconds from datetime.now() in Python 

.%f  dot... period

JoeBorgione
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....
0 Kudos