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.

Answer from steveha on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types — Python 3.14.3 documentation
'seconds': Include hour, minute, and second in HH:MM:SS format. 'milliseconds': Include full time, but truncate fractional second part to milliseconds. HH:MM:SS.sss format. 'microseconds': Include full time in HH:MM:SS.ffffff format.
🌐
YouTube
youtube.com › codelearn
python time format milliseconds 3 digits - YouTube
Download this code from https://codegive.com When working with time in Python, you may encounter situations where you need to work with milliseconds and repr...
Published   December 14, 2023
Views   256
🌐
Esri Community
community.esri.com › t5 › python-questions › milliseconds-with-strftime › td-p › 73258
Solved: Milliseconds with strftime - Esri Community
December 10, 2021 - from datetime import datetime curr_time = datetime.now() formatted_time = curr_time.strftime('%H:%M:%S.%f') print(formatted_time) 18:41:59.891075‍‍‍‍‍‍‍‍‍‍‍‍‍‍ · How to get min, seconds and milliseconds from datetime.now() in Python
🌐
Python.org
discuss.python.org › ideas
Add millisecond formatting support to datetime.strftime - Ideas - Discussions on Python.org
November 28, 2025 - Hi, I’d like to propose adding native support for millisecond precision formatting in Python’s datetime.strftime() API. Currently, Python provides: %f in strftime() for microseconds (6 digits) datetime.isoformat(…
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › convert datetime into string with milliseconds in python (3 examples)
Convert datetime into String with Milliseconds in Python (3 Examples)
January 26, 2023 - my_string1 = my_datetime.isoformat(sep = ' ', timespec = 'milliseconds') print(my_string1) # 2021-11-25 13:36:44.396 · As you can see, we have created a new data object called my_string1 that contains our example date with milliseconds formatted as a string.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-use-strptime-with-milliseconds-in-python
How to use strptime with milliseconds in Python - GeeksforGeeks
April 17, 2025 - Here's how to do it: ... from datetime ... = datetime.strptime(s, format) print(dt_obj) ... Use %f when you want to include milliseconds or microseconds in your datetime string....
🌐
Delft Stack
delftstack.com › home › howto › python › python datetime milliseconds
How to Convert DateTime to String With Milliseconds in Python | Delft Stack
February 2, 2024 - This method is faster than the above methods, but we could specify the string format. We can also simply remove the last three digits from the string to get the final result in milliseconds.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-use-strptime-with-milliseconds-in-python
How to use strptime with milliseconds in Python
October 13, 2023 - The following example shows the ... is passed as the format parameter to this method, the formatting will default to "%a %b %d %H:%M:%S %Y" making it similar to the return value of the ctime() method....
🌐
GitHub
github.com › selectel › tempo › issues › 1
milliseconds in strptime and strftime · Issue #1 · selectel/tempo
June 25, 2012 - tempo:parse(iso8601, {datetime, }). ** exception error: no match of right hand side value {error,format_mism...
Author   2garryn
🌐
GitHub
gist.github.com › jarek › 354423854a7cc20b1e91
rounding microseconds for display in python · GitHub
rounding microseconds for display in python. GitHub Gist: instantly share code, notes, and snippets.
🌐
WordPress
mike632t.wordpress.com › 2021 › 05 › 02 › formatting-time-with-milliseconds-in-python
Formatting time with milliseconds in Python | Notes on Linux
May 2, 2021 - If you are prepared to store the time in a variable and do a little string manipulation, then you can display the date and time including the milliseconds without using the datetime module. >>> _now = time.time() >>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)), ... str('%.3f'%_now).split('.')[1])) # Rounds to nearest millisecond Time : 05/02/21 01:16:58.676>>> The nice thing about this approach is that because the number of seconds is being formatted as a…
🌐
APIdock
apidock.com › ruby › v1_9_3_392 › DateTime › strftime
strftime (DateTime) - APIdock
20 in 2009) %y - year % 100 (00..99) ... of the hour (00..59) %S - Second of the minute (00..59) %L - Millisecond of the second (000..999) %N - Fractional seconds digits, default is 9 digits (nanosecond) %3N millisecond (3 digits) %6N microsecond (6 digits) %9N nanosecond (9 ...
🌐
Restack
restack.io › p › datetime-manipulation-techniques-knowledge-answer-datetime-format-python-milliseconds
Datetime Format Python Milliseconds | Restackio
May 3, 2025 - This code snippet demonstrates how to format the current datetime to include milliseconds. The [:-3] slice removes the last three digits of the microseconds to convert them into milliseconds.
🌐
py4u
py4u.org › blog › python-time-milli-seconds-calculation
How to Calculate Milliseconds in Python Using datetime Module: A Practical Guide
To include milliseconds in a formatted string, manually extract the microseconds, convert to milliseconds, and append them to the string. ... from datetime import datetime # Create a datetime object with microseconds dt = datetime(2024, 5, 20, ...
🌐
GeeksforGeeks
geeksforgeeks.org › parsing-datetime-strings-containing-nanoseconds-in-python
Parsing DateTime strings containing microseconds in Python - GeeksforGeeks
February 16, 2023 - Python has a list of directives ... be using in our codes. ... Let us take the default Python timestamp format: "2021-08-05 15:25:56.792554" as an example to work on....
🌐
GitHub
github.com › moment › luxon › issues › 1156
Unable to parse 7 digit milliseconds · Issue #1156 · moment/luxon
March 8, 2022 - To Reproduce We have tried different combinations: DateTime.fromFormat('2022-01-25 00:06:30.1590000', 'yyyy-MM-dd HH:mm:ss.S') DateTime.fromFormat('2022-01-25 00:06:30.1590000', 'yyyy-MM-dd HH:mm:ss.SSSSSS') Actual vs Expected behavior Expected ...
Author   w-a-b