Search code examples
pythondate-format

How to get real three digits of microseconds in Python?


I'm trying to increase the time.

I want to get an hour format like this: 13:30:45,123 (in Java: "HH:mm:ss,SSS"), but Python displays 13:30:45,123456 ("%H:%M:%S,%f")(microseconds of 6 digits).

I read on the web and found possible solutions like:

from datetime import datetime
hour = datetime.utcnow().strftime('%H:%M:%S,%f')[:-3]
print(hour)

The output is: 04:33:16,123

But it's a bad solution, because if the hour is for example: 01:49:56,020706, the output is: 01:49:56,020, that the right should be: 01:49:56,021 (rounded).


The real purpose is that if I increase the milliseconds, even reaching rounds the seconds.
Example: (I want to increase 500 microseconds)

If the Input: 00:01:48,557, the Output should be: 00:01:49,057

The code of the program in Java (working good) is:

SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss,SSS");            
System.out.print("Input the time: ");
t1 = in.next();

Date d = df.parse(t1);
Calendar cal = Calendar.getInstance();            
cal.setTime(d);
cal.add(Calendar.MILLISECOND, 500);//here increase the milliseconds (microseconds)

t2 = df.format(cal.getTime());            
System.out.print("The Output (+500): "+t2);

I don't know if exists in Python something like SimpleDateFormat (in Java).


Solution

  • As to addition, you can add 500ms to your datetime object, using a timedelta object:

    from datetime import datetime, timedelta
    t1 = datetime.utcnow()
    t2 = t1 + timedelta(milliseconds=500)
    

    So as long as you're working with datetime objects instead of strings, you can easily do all the time-operations you'd like.

    So we're left with the question of how to format the time when you want to display it.

    As you pointed out, the [:-3]-trick seems to be the common solution, and seems to me it should work fine. If you really care about rounding correctly to the closest round millisecond, you can use the following "rounding trick":

    You must have seen this trick in the past, for floats:

    def round(x):
        return int(x + 0.5)
    

    The same idea (i.e. adding 0.5) can also be applied to datetimes:

    def format_dt(t):
        tr = t + timedelta(milliseconds=0.5)
        return tr.strftime('%H:%M:%S,%f')[:-3]