150

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
oakbramble
  • 1,637
  • 2
  • 11
  • 7

8 Answers8

225

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!

Nam G VU
  • 33,193
  • 69
  • 233
  • 372
adamnfish
  • 10,935
  • 4
  • 31
  • 40
  • 2
    Not if you want to use `%z` – vallentin Feb 12 '17 at 00:25
  • @Vallentin pretty sure it's the opposite! `datetime` [supports the `%z` directive](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) while [time doesn't appear to](https://docs.python.org/2/library/time.html#time.strftime). – adamnfish Feb 13 '17 at 17:00
  • Both support `%z` in Python 3 :-) [here's datetime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) and then [time](https://docs.python.org/3/library/time.html#time.strftime) – adamnfish Feb 13 '17 at 17:55
  • 1
    Ohh you're right. I missed it on datetime since it wasn't at the bottom, like on the table for time. :P – vallentin Feb 13 '17 at 19:57
  • 7
    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")` – JBaczuk Aug 29 '17 at 20:21
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'
Craig McQueen
  • 41,871
  • 30
  • 130
  • 181
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
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
>>>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
baltasvejas
  • 1,698
  • 2
  • 17
  • 18
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

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
salah Laaroussi
  • 175
  • 1
  • 2
  • 5
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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2189872
  • 77
  • 1
  • 3
  • 3
    This won't work if the dt.microsecond has less than 6 digits. – M456 Jun 24 '14 at 20:29
  • 3
    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] – Ed Randall Jun 09 '15 at 11:59
  • 1
    str(dt.microsecond)[0:3] might produce a wrong result (e.g. 300 microseconds are 0.300 milleseconds, but it will print 300!) – cabbi Nov 09 '15 at 15:15
  • 3
    "%03d"%int(dt.microsecond/1000) -> this prints the millseconds and not microseconds – cabbi Mar 08 '16 at 08:34
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)
Pushpak Dagade
  • 6,280
  • 7
  • 28
  • 41
  • 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. – oakbramble Jul 13 '11 at 13:20
0

If you want an integer, try this code:

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

Output:

1545474382803
Rafal Enden
  • 3,028
  • 1
  • 21
  • 16
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.

mato
  • 593
  • 4
  • 11