Python
datetime
time parsing
milliseconds
programming

How can I parse a time string containing milliseconds in it with python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, time strings with milliseconds are usually parsed with datetime.strptime and the %f directive. The important detail is that %f handles fractional seconds, so the parsing job is mostly about matching the incoming format exactly and then deciding whether you need only a time, a full datetime, or timezone-aware data.

Use %f for Fractional Seconds

Python’s datetime parser uses %f for microseconds, and it accepts millisecond-style input as part of that fractional field.

python
1from datetime import datetime
2
3text = "12:34:56.789"
4dt = datetime.strptime(text, "%H:%M:%S.%f")
5
6print(dt)
7print(dt.time())

Even though the input has only three fractional digits, Python still parses it correctly. Internally it normalizes the value into microseconds.

If you want only the time object:

python
parsed_time = dt.time()
print(parsed_time)

That is useful when the input string contains no date and your application logic only cares about time-of-day.

Parse Full Datetime Strings the Same Way

If the string includes both date and time, keep %f in the same place relative to the separator.

python
1from datetime import datetime
2
3text = "2026-03-11 12:34:56.789"
4dt = datetime.strptime(text, "%Y-%m-%d %H:%M:%S.%f")
5
6print(dt)

The pattern is unchanged:

  • write the date tokens
  • write the time tokens
  • add %f for the fractional part

Parsing gets simpler when the format is stated explicitly rather than guessed.

Handle Optional Milliseconds Deliberately

One common annoyance is input that sometimes includes milliseconds and sometimes does not. In that case, use a small fallback sequence instead of one overly clever parser.

python
1from datetime import datetime
2
3
4def parse_time(value: str) -> datetime:
5    formats = ["%H:%M:%S.%f", "%H:%M:%S"]
6    for fmt in formats:
7        try:
8            return datetime.strptime(value, fmt)
9        except ValueError:
10            pass
11    raise ValueError(f"Unsupported time format: {value}")
12
13
14print(parse_time("12:34:56.789"))
15print(parse_time("12:34:56"))

This is often clearer than trying to preprocess the string in awkward ways.

Watch Out for Time Zones

If the string includes a timezone suffix, the format must include that too. For example:

python
1from datetime import datetime
2
3text = "2026-03-11 12:34:56.789+0000"
4dt = datetime.strptime(text, "%Y-%m-%d %H:%M:%S.%f%z")
5
6print(dt)

Without %z, the same string will fail to parse. Time parsing bugs are often format bugs rather than library bugs.

If the string is ISO 8601-like, fromisoformat may be simpler:

python
1from datetime import datetime
2
3text = "2026-03-11T12:34:56.789+00:00"
4dt = datetime.fromisoformat(text)
5print(dt)

That is often cleaner when the input is already close to standard ISO form.

Parse First, Then Reformat if Needed

After parsing, you can format the result however you want.

python
1from datetime import datetime
2
3text = "12:34:56.789"
4dt = datetime.strptime(text, "%H:%M:%S.%f")
5print(dt.strftime("%H:%M:%S"))

This is the right pattern if the real task is conversion rather than just parsing.

Common Pitfalls

  • Forgetting %f is the direct cause of most failures when the input includes milliseconds.
  • Assuming %f requires exactly six digits is wrong; Python accepts shorter fractional input and normalizes it.
  • Mixing time-only and full-datetime formats without separate parsing rules makes the code brittle.
  • Ignoring timezone suffixes causes valid timestamp strings to fail unexpectedly.
  • Slicing off the fractional part manually before parsing often throws away useful precision unnecessarily.

Summary

  • Use datetime.strptime(..., "%H:%M:%S.%f") for time strings that include milliseconds.
  • '%f handles fractional seconds and works even when the input has only three digits.'
  • Add the corresponding date and timezone directives when the input string includes them.
  • Use fallback formats when milliseconds are optional.
  • Parse into a datetime object first, then reformat only if the application needs a different output shape.

Course illustration
Course illustration

All Rights Reserved.