pythondatetimeformatter

datetime: Round/trim number of digits in microseconds


Currently I am logging stuff and I am using my own formatter with a custom formatTime():

def formatTime(self, _record, _datefmt):
    t = datetime.datetime.now()
    return t.strftime('%Y-%m-%d %H:%M:%S.%f')

My issue is that the microseconds, %f, are six digits. Is there anyway to spit out less digits, like the first three digits of the microseconds?


Solution

  • The simplest way would be to use slicing to just chop off the last three digits of the microseconds:

    def format_time():
        t = datetime.datetime.now()
        s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
        return s[:-3]
    

    I strongly recommend just chopping. I once wrote some logging code that rounded the timestamps rather than chopping, and I found it actually kind of confusing when the rounding changed the last digit. There was timed code that stopped running at a certain timestamp yet there were log events with that timestamp due to the rounding. Simpler and more predictable to just chop.

    If you want to actually round the number rather than just chopping, it's a little more work but not horrible:

    def format_time():
        t = datetime.datetime.now()
        s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
        head = s[:-7] # everything up to the '.'
        tail = s[-7:] # the '.' and the 6 digits after it
        f = float(tail)
        temp = "{:.03f}".format(f)  # for Python 2.x: temp = "%.3f" % f
        new_tail = temp[1:] # temp[0] is always '0'; get rid of it
        return head + new_tail
    

    Obviously you can simplify the above with fewer variables; I just wanted it to be very easy to follow.