Python
datetime
string manipulation
timestamp formatting
code examples

Python datetime to string without microsecond component

Master System Design with Codemia

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

Introduction

Formatting a Python datetime without microseconds is a common requirement for logs, APIs, filenames, and user-facing timestamps. The main design choice is whether you only want to suppress microseconds in the final string or whether you want to truncate the datetime object itself before further processing.

Python gives you both options. strftime and isoformat(timespec="seconds") control the output string, while replace(microsecond=0) changes the precision of the datetime object itself.

Use strftime for Full Control

If you know the exact string format you want, strftime is the most direct approach:

python
1from datetime import datetime
2
3now = datetime.now()
4text = now.strftime("%Y-%m-%d %H:%M:%S")
5print(text)

Because %f is not included in the format string, microseconds do not appear.

This is a good choice for log lines, filenames, and fixed-format text output where you want total control over the shape of the result.

Use isoformat With timespec

If you want an ISO-style timestamp, datetime.isoformat can control the precision directly:

python
1from datetime import datetime
2
3now = datetime.now()
4print(now.isoformat(timespec="seconds"))

This is often cleaner than building the ISO pattern manually, and it makes the intent clear: ISO output with second-level precision.

Truncate the Datetime Object Itself

Sometimes the real need is not only a cleaner string. You may want a datetime value that no longer carries microseconds:

python
1from datetime import datetime
2
3now = datetime.now()
4trimmed = now.replace(microsecond=0)
5
6print(trimmed)
7print(trimmed.isoformat())

This matters when the truncated value is going to be stored, compared, or passed into another function that should not see sub-second precision.

Keep Timezones Explicit

When timestamps cross machines or services, include timezone data. Second-level precision is not enough if the timezone is ambiguous:

python
1from datetime import datetime, timezone
2
3now_utc = datetime.now(timezone.utc).replace(microsecond=0)
4print(now_utc.isoformat())

For API payloads, a helper often keeps the policy consistent:

python
1from datetime import datetime, timezone
2
3
4def format_timestamp(dt: datetime) -> str:
5    if dt.tzinfo is None:
6        dt = dt.replace(tzinfo=timezone.utc)
7    dt = dt.astimezone(timezone.utc).replace(microsecond=0)
8    return dt.isoformat().replace("+00:00", "Z")
9
10
11print(format_timestamp(datetime.now(timezone.utc)))

This enforces both UTC and second-level precision in one place.

Parse and Reformat Existing Strings

If the input string already includes microseconds, parse it and then reformat:

python
1from datetime import datetime
2
3raw = "2026-03-04 14:22:13.987654"
4dt = datetime.strptime(raw, "%Y-%m-%d %H:%M:%S.%f")
5clean = dt.strftime("%Y-%m-%d %H:%M:%S")
6
7print(clean)

This is useful when you need to normalize timestamps from inconsistent upstream systems.

Keep Display Formatting Separate From Storage Formatting

Human-facing timestamps and machine-facing timestamps often have different requirements. A UI string may want month names and local time:

python
1from datetime import datetime
2
3dt = datetime.now().replace(microsecond=0)
4print(dt.strftime("%d %b %Y %H:%M:%S"))

An API payload may want UTC ISO format instead. Keeping these responsibilities separate prevents accidental drift between logs, storage, and user interfaces.

Common Pitfalls

The biggest mistake is removing microseconds only from the displayed string while keeping mixed precision in stored values. That can cause confusing comparisons later.

Another common problem is ignoring timezones. A timestamp without microseconds can still be wrong or ambiguous if the timezone policy is inconsistent.

People also assume str(datetime_obj) always matches the required format. It does not. Use an explicit formatting method when the output shape matters.

Finally, be deliberate about where truncation happens. If you only want display formatting, do not mutate the data value unnecessarily.

Summary

  • Use strftime when you want full control over the output string.
  • Use isoformat(timespec="seconds") for concise ISO formatting without microseconds.
  • Use replace(microsecond=0) when the datetime object itself should lose sub-second precision.
  • Keep timezone handling explicit, especially for APIs and distributed systems.
  • Separate machine-facing and user-facing timestamp formatting policies.

Course illustration
Course illustration

All Rights Reserved.