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

8

156

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.)

Swill answered 13/7, 2011 at 10:15 Comment(0)
U
229

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!

Unusual answered 13/7, 2011 at 10:53 Comment(5)
Not if you want to use %zExpress
@Vallentin pretty sure it's the opposite! datetime supports the %z directive while time doesn't appear to.Unusual
Both support %z in Python 3 :-) here's datetime and then timeUnusual
Ohh you're right. I missed it on datetime since it wasn't at the bottom, like on the table for time. :PExpress
note the from datetime import datetime. If you just do import datetime you will have to use datetime.datetime.now().strftime("%H:%M:%S.%f")Isoagglutination
J
40

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'
Jemappes answered 13/7, 2011 at 10:19 Comment(3)
Here's the link to the datetime module's documentation: docs.python.org/2/library/…Antrum
Thanks for the post. Why is there a datetime and time module?Fuld
#7480277Weintrob
F
16

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 timestamp
now = time.time()

# Debug now
now
print now
type(now)

# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)

# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)

# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec

# Get your required timestamp string
timestamp = 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
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.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 mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>
For answered 16/1, 2017 at 14:56 Comment(0)
P
7

This should do the work

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

It will print

HH:MM:SS.microseconds like this e.g 14:38:19.425961

Penthouse answered 29/4, 2014 at 14:10 Comment(0)
H
5

You can also get microsecond precision from the time module using its time() function.
(time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)
Humpage answered 13/7, 2011 at 11:0 Comment(1)
Excellent. Thanks for all your help. I've managed to get things working, though found an odd bug that means microseconds don't appear when running the script as sudo on a particular cset, but do if I log in as sudo before trying to run it on a particular cset. Odd.Swill
M
5

When the "%f" for micro seconds isn't working, please use the following method:

import datetime

def getTimeStamp():
    dt = datetime.datetime.now()
    return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)
Martinic answered 24/6, 2013 at 8:20 Comment(4)
This won't work if the dt.microsecond has less than 6 digits.Marquez
This was the only solution that actually worked for me. In Jython on Windows %f seems to always print a literal %f. I wanted milliseconds so used str(dt.microsecond)[0:3]Haunch
str(dt.microsecond)[0:3] might produce a wrong result (e.g. 300 microseconds are 0.300 milleseconds, but it will print 300!)Neutrino
"%03d"%int(dt.microsecond/1000) -> this prints the millseconds and not microsecondsNeutrino
F
0

If you want an integer, try this code:

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

Output:

1545474382803
Fabiola answered 22/12, 2018 at 10:27 Comment(0)
O
0

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.

Overdraft answered 7/8, 2019 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.