Search code examples
pythondatetimemilliseconds

Why are three extra zeros added in the datetime.time milliseconds field?


I'm parsing through a log file and saving different values in different variable. When I insert milliseconds in datetime.time(hour,minute,second,millisecond) it adds three extra zeros in front of the millisecond value, why?

lst = ['13', '33', '30.913']
hour = int(time[0], 10)
minute = int(time[1], 10)
second = int((time[2].split('.'))[0], 10)
millisecond = int((time[2].split('.'))[1], 10)
print(millisecond)
time = datetime.time(hour, minute, second, millisecond)
print(time)

I expect 13:33:30:913 from print(time), but the actual output is 13:33:30:000913

However the output from print(millisecond) is 913, which is correct.


Solution

  • The 4th argument to datetime.time is actually microsecond and not millisecond:

    datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

    In order to make your code work you should multiply your millisecond by 1000 and printing can be done using the isoformat method:

    time = datetime.time(hour, minute, second, millisecond * 1000)
    print(time.isoformat('milliseconds'))