Skip to content
shellhacks.dev
Python

Parse a date and print another format

Parse a date string with datetime.strptime and print it in another format with strftime. The two format strings use the same codes but run in opposite directions.

1 min read
Summarize in AI

A date arrives as 05/03/2026 and the next system wants 2026-03-05.

Python
from datetime import datetime

d = datetime.strptime("05/03/2026", "%d/%m/%Y")
print(d.strftime("%Y-%m-%d"))
print(d.strftime("%A %d %B %Y"))
print(d.date().isoformat())

try:
    datetime.strptime("05/03/2026", "%m-%d-%Y")
except ValueError as e:
    print("ValueError:", e)
Text
2026-03-05
Thursday 05 March 2026
2026-03-05
ValueError: time data '05/03/2026' does not match format '%m-%d-%Y'

strptime reads a string into a datetime using a format, and strftime writes a datetime out with another one. Both use the codes in the format code table. A format that does not match the text raises ValueError, which the last block prints, so a bad input never turns into a wrong date. For ISO output isoformat() needs no format at all.

Month and day names follow the process locale, which is C unless the program changes it. Day first or month first is a property of the data, not the code: 05/03/2026 is read as March 5 here only because the format says so. %z parses offsets, and a result without one is a naive datetime that carries no zone.

Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.