datetime: Round/trim number of digits in microseconds

PythonDatetimeFormatter

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

As of Python 3.6 the language has this feature built in:

def format_time():
    t = datetime.datetime.now()
    s = t.isoformat(timespec='milliseconds')
    return s

Solution 3 - Python

This method should always return a timestamp that looks exactly like this (with or without the timezone depending on whether the input dt object contains one):

2016-08-05T18:18:54.776+0000

It takes a datetime object as input (which you can produce with datetime.datetime.now()). To get the time zone like in my example output you'll need to import pytz and pass datetime.datetime.now(pytz.utc).

import pytz, datetime


time_format(datetime.datetime.now(pytz.utc))

def time_format(dt):
    return "%s:%.3f%s" % (
        dt.strftime('%Y-%m-%dT%H:%M'),
        float("%.3f" % (dt.second + dt.microsecond / 1e6)),
        dt.strftime('%z')
    )   

I noticed that some of the other methods above would omit the trailing zero if there was one (e.g. 0.870 became 0.87) and this was causing problems for the parser I was feeding these timestamps into. This method does not have that problem.

Solution 4 - Python

An easy solution that should work in all cases:

def format_time():
    t = datetime.datetime.now()
    if t.microsecond % 1000 >= 500:  # check if there will be rounding up
        t = t + datetime.timedelta(milliseconds=1)  # manually round up
    return t.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

Basically you do manual rounding on the date object itself first, then you can safely trim the microseconds.

Solution 5 - Python

Edit: As some pointed out in the comments below, the rounding of this solution (and the one above) introduces problems when the microsecond value reaches 999500, as 999.5 is rounded to 1000 (overflow).

Short of reimplementing strftime to support the format we want (the potential overflow caused by the rounding would need to be propagated up to seconds, then minutes, etc.), it is much simpler to just truncate to the first 3 digits as outlined in the accepted answer, or using something like:

'{:03}'.format(int(999999/1000))

-- Original answer preserved below --

In my case, I was trying to format a datestamp with milliseconds formatted as 'ddd'. The solution I ended up using to get milliseconds was to use the microsecond attribute of the datetime object, divide it by 1000.0, pad it with zeros if necessary, and round it with format. It looks like this:

'{:03.0f}'.format(datetime.now().microsecond / 1000.0)
# Produces: '033', '499', etc.

Solution 6 - Python

You can subtract the current datetime from the microseconds.

d = datetime.datetime.now()
current_time = d - datetime.timedelta(microseconds=d.microsecond)

This will turn 2021-05-14 16:11:21.916229 into 2021-05-14 16:11:21

Solution 7 - Python

This method allows flexible precision and will consume the entire microsecond value if you specify too great a precision.

def formatTime(self, _record, _datefmt, precision=3):
    dt = datetime.datetime.now()
    us = str(dt.microsecond)
    f = us[:precision] if len(us) > precision else us
    return "%d-%d-%d %d:%d:%d.%d" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, int(f))

This method implements rounding to 3 decimal places:

import datetime
from decimal import *

def formatTime(self, _record, _datefmt, precision='0.001'):
    dt = datetime.datetime.now()
    seconds = float("%d.%d" % (dt.second, dt.microsecond))
    return "%d-%d-%d %d:%d:%s" % (dt.year, dt.month, dt.day, dt.hour, dt.minute,
                             float(Decimal(seconds).quantize(Decimal(precision), rounding=ROUND_HALF_UP)))

I avoided using the strftime method purposely because I would prefer not to modify a fully serialized datetime object without revalidating it. This way also shows the date internals in case you want to modify it further.

In the rounding example, note that the precision is string-based for the Decimal module.

Solution 8 - Python

Here is my solution using regexp:

import re

# Capture 6 digits after dot in a group.
regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
    """Converts the datetime object to Splunk isoformat string."""
    # 6-digits string.
    microseconds = regexp.search(dt.isoformat()).group(1)
    return regexp.sub('.%d' % round(float(microseconds) / 1000), dt.isoformat())

Solution 9 - Python

Fixing the proposed solution based on Pablojim Comments:

from datetime import datetime

dt = datetime.now()
 
dt_round_microsec = round(dt.microsecond/1000) #number of zeroes to round   
dt = dt.replace(microsecond=dt_round_microsec)

Solution 10 - Python

If once want to get the day of the week (i.e, 'Sunday)' along with the result, then by slicing '[:-3]' will not work. At that time you may go with,

dt = datetime.datetime.now()
print("{}.{:03d} {}".format(dt.strftime('%Y-%m-%d %I:%M:%S'), dt.microsecond//1000, dt.strftime("%A")))

#Output: '2019-05-05 03:11:22.211 Sunday'

%H - for 24 Hour format

%I - for 12 Hour format

Thanks,

Solution 11 - Python

Adding my two cents here as this method will allow you to write your microsecond format as you would a float in c-style. It takes advantage that they both use %f.

import datetime
import re

def format_datetime(date, format):
    """Format a ``datetime`` object with microsecond precision.
       Pass your microsecond as you would format a c-string float.
       e.g "%.3f"

       Args:
            date (datetime.datetime): You input ``datetime`` obj.
            format (str): Your strftime format string.

        Returns:
            str: Your formatted datetime string.
    """
    # We need to check if formatted_str contains "%.xf" (x = a number) 
    float_format = r"(%\.\d+f)"
    has_float_format = re.search(float_format, format)
    if has_float_format:
        # make microseconds be decimal place. Might be a better way to do this
        microseconds = date.microsecond
        while int(microseconds):  # quit once it's 0
            microseconds /= 10
        ms_str = has_float_format.group(1) % microseconds
        format = re.sub(float_format, ms_str[2:], format)
    return date.strftime(format)

print(datetime.datetime.now(), "%H:%M:%S.%.3f")
# '17:58:54.424'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParhamView Question on Stackoverflow
Solution 1 - PythonstevehaView Answer on Stackoverflow
Solution 2 - PythonRobView Answer on Stackoverflow
Solution 3 - PythonEric HerotView Answer on Stackoverflow
Solution 4 - PythonAbdurrahmanView Answer on Stackoverflow
Solution 5 - PythonApteryxView Answer on Stackoverflow
Solution 6 - PythonuserView Answer on Stackoverflow
Solution 7 - PythonNuclearPeonView Answer on Stackoverflow
Solution 8 - PythoniuriiView Answer on Stackoverflow
Solution 9 - PythongandreotiView Answer on Stackoverflow
Solution 10 - PythonJai KView Answer on Stackoverflow
Solution 11 - PythonLiam HoflayView Answer on Stackoverflow