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

前端 未结 8 1920
渐次进展
渐次进展 2020-11-29 21:32

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
im         


        
相关标签:
8条回答
  • 2020-11-29 22:05

    If you want an integer, try this code:

    import datetime
    print(datetime.datetime.now().strftime("%s%f")[:13])
    

    Output:

    1545474382803
    
    0 讨论(0)
  • 2020-11-29 22:05

    If you want speed, try this:

    def _timestamp(prec=0):
        t = time.time()
        s = time.strftime("%H:%M:%S", time.localtime(t))
        if prec > 0:
            s += ("%.9f" % (t % 1,))[1:2+prec]
        return s
    

    Where prec is precision -- how many decimal places you want. Please note that the function does not have issues with leading zeros in fractional part like some other solutions presented here.

    0 讨论(0)
提交回复
热议问题