Q&A library Python

How do I convert between strings and dates in Python with strptime and strftime?

Python Intermediate datetimestrftimestrptime

Short answer

strptime parses a string into a datetime using a format code, and strftime formats a datetime back into a string. The format codes must match the text exactly, and mixing the two directions is the usual mistake.

The short version

strptime parses a string into a datetime using a format that describes the text, and strftime formats a datetime back into a string. The trick is to write the format codes so they match the text exactly. The common confusion is which direction is which: parse comes in (p for parse), format goes out.

Parsing text into a date

from datetime import datetime

d = datetime.strptime("2021-03-15", "%Y-%m-%d")
print(d)   # 2021-03-15 00:00:00

The format "%Y-%m-%d" says four-digit year, dash, two-digit month, dash, two-digit day. Every literal character in the text, including the dashes, must appear in the format string too.

Formatting a date into text

print(d.strftime("%d %b %Y"))   # 15 Mar 2021

strftime uses the same codes to build a string in whatever layout you want. Here %b is the abbreviated month name, giving a human-friendly format.

The format codes to know

The essentials are %Y (four-digit year), %m (month number), %d (day), %H (24-hour), %M (minute), %S (second), %b (short month name) and %A (weekday name). A frequent slip is %m versus %M: lowercase is month, uppercase is minute. Mixing them gives silently wrong results.

The exact-match requirement

strptime fails if the format does not match the text precisely. A string like "15/03/2021" needs "%d/%m/%Y", not "%Y-%m-%d", or it raises ValueError. Match the separators and order exactly, and remember the ambiguity of day-first versus month-first: 03/04/2021 needs you to know which your data uses.

Doing this in pandas instead

For a whole column, do not loop with strptime. Use pd.to_datetime, which is vectorised and accepts the same format codes.

import pandas as pd
pd.to_datetime(df["date"], format="%d/%m/%Y")

Passing an explicit format is faster and safer than letting pandas guess, especially on ambiguous dates. Use the standard library strptime for one-off single values, and to_datetime for columns.

Locale and month names

Codes that produce names, like %b and %A, follow the system locale, so month and day names may appear in another language on a differently configured machine. If you need stable English names regardless of locale, format from the numeric parts yourself or set the locale explicitly, because relying on the default can produce surprising output on another system.

Enjoying these?

Go from piecing together answers to real fluency.

Our courses take you from looking things up to doing the work with confidence, step by step on real data.

Browse the courses