date conversion
date formatting
string manipulation
programming
datetime conversion

How do I convert a date/time string into a different date string?

Master System Design with Codemia

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

Introduction

Converting one date/time string format into another is a two-step job: parse the input into a real date object, then format that object into the target string. Most bugs happen when code skips the parsing step, ignores time zones, or guesses the input format instead of stating it explicitly.

Parse First, Then Format

Treat the input string as data that must be interpreted, not as text that should be sliced manually. In Python, datetime.strptime is a reliable way to parse known formats.

python
1from datetime import datetime
2
3source = "2026-03-11 14:35:00"
4dt = datetime.strptime(source, "%Y-%m-%d %H:%M:%S")
5result = dt.strftime("%d/%m/%Y")
6
7print(result)  # 11/03/2026

That pattern scales well because it keeps the input format and the output format explicit.

If your input is ISO 8601, parsing can be even simpler.

python
1from datetime import datetime
2
3source = "2026-03-11T14:35:00+00:00"
4dt = datetime.fromisoformat(source)
5print(dt.strftime("%b %d, %Y"))

The key idea is that once the string becomes a date object, output formatting becomes routine.

Handle Time Zones Deliberately

Many conversion bugs are not format bugs at all. They are timezone bugs. A timestamp like 2026-03-11T00:30:00+00:00 may belong to a different calendar day in another timezone.

python
1from datetime import datetime
2from zoneinfo import ZoneInfo
3
4source = "2026-03-11T00:30:00+00:00"
5dt_utc = datetime.fromisoformat(source)
6dt_toronto = dt_utc.astimezone(ZoneInfo("America/Toronto"))
7
8print(dt_utc.strftime("%Y-%m-%d %H:%M %Z"))
9print(dt_toronto.strftime("%Y-%m-%d %H:%M %Z"))

If the goal is a user-facing local date, convert to the correct timezone before formatting. If the goal is storage or API transfer, keep the value in UTC and format accordingly.

Validate Uncertain Input

Real systems rarely receive perfect date strings. If the format may vary or be malformed, catch parsing errors and decide on a policy.

python
1from datetime import datetime
2
3def convert_date_string(value: str) -> str | None:
4    try:
5        dt = datetime.strptime(value, "%m/%d/%Y %H:%M")
6    except ValueError:
7        return None
8    return dt.strftime("%Y-%m-%d")
9
10print(convert_date_string("03/11/2026 09:15"))
11print(convert_date_string("not-a-date"))

Returning None, raising an error, or logging and skipping are all valid choices. The important part is being intentional instead of silently producing a wrong result.

Use the Standard Library Before Reaching for Regex

People often try to convert dates with string splitting or regular expressions:

python
parts = "2026-03-11".split("-")
print(parts[2] + "/" + parts[1] + "/" + parts[0])

That can appear to work for one happy-path input, but it breaks as soon as:

  • the string includes a timezone
  • the separator changes
  • the input includes a time component
  • the order is ambiguous between day and month

Date libraries already understand these rules. Let them do the job.

A Reusable Conversion Helper

A small helper can centralize conversion logic in one place.

python
1from datetime import datetime
2
3def reformat_date(value: str, source_fmt: str, target_fmt: str) -> str:
4    dt = datetime.strptime(value, source_fmt)
5    return dt.strftime(target_fmt)
6
7
8print(reformat_date("11-03-2026 18:05", "%d-%m-%Y %H:%M", "%Y/%m/%d"))

This is especially useful in ETL scripts, import pipelines, and CSV cleanup code where the same transformation happens repeatedly.

Common Pitfalls

  • Trying to transform date strings with plain slicing instead of parsing them as dates.
  • Ignoring timezone conversion when the output date is user-facing or locale-sensitive.
  • Assuming ambiguous formats such as 03/04/2026 mean the same thing everywhere.
  • Swallowing parse failures and continuing with bad data.
  • Reformatting the string without checking whether the input includes both date and time parts.

Summary

  • Convert date strings by parsing into a datetime object first, then formatting the result.
  • Keep both the source format and target format explicit in code.
  • Handle time zones before formatting when the displayed date depends on locale.
  • Validate uncertain input and choose a clear error policy.
  • Prefer the standard date library over manual string slicing or regex shortcuts.

Course illustration
Course illustration

All Rights Reserved.