Fundamentals 7 min read

Understanding and Avoiding Common Mistakes with Python datetime.strptime and strftime

The article explains why Python developers often swap the arguments of datetime.strptime, analyzes the naming and semantics of strptime and strftime, demonstrates correct usage with code examples, and discusses the source‑to‑destination pattern and related special cases such as regex and string methods.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding and Avoiding Common Mistakes with Python datetime.strptime and strftime

Even experienced Python users frequently reverse the arguments of datetime.strptime(string, format) , writing datetime.strptime(format, string) , and confuse it with re.find(pattern, string) .

Analysis of the problem

1. datetime.strptime()

The function name is ambiguous; a clearer name like str2time would emphasize that a source string is parsed into a time object. The official name includes the verb parse , highlighting its core logic.

<code>strptime(string, format) method of builtins.type instance
    string, format -> new datetime parsed from a string (like time.strptime())
#Case
In [6]: datetime.strptime("8 May, 2019", "%d %B, %Y")
Out[6]: datetime.datetime(2019, 5, 8, 0, 0)
</code>

The function works by parsing a string to produce a time object, following the source‑to‑destination pattern.

We can extend the parameter names for clarity:

<code>datetime.strptime(string, format)
# extended as
def strptime(src_string, parsed_format) -> "dst_time_object":
    ...
</code>

Because re.match(pattern, string) places the pattern first, some developers mistakenly put the format first in strptime . However, strptime(string, format) adheres to the conventional source‑to‑destination order.

2. datetime.strftime()

The inverse function strftime(format) (or time2str ) also follows the source‑to‑destination principle, which can lead to the same confusion when users write the format before the string.

<code>In [8]: dt
Out[8]: datetime.datetime(2019, 5, 8, 0, 0)
In [9]: dt.strftime("%d %B, %Y")
Out[9]: '08 May, 2019'
</code>

Using the functional form:

<code>In [9]: datetime.strftime(datetime.now(), "%b %d %Y %H:%M:%S")
Out[9]: 'Jun 11 2020 08:08:52'
</code>

Both functions thus respect the src to dst rule.

3. Special cases and regular patterns

Besides regex methods, most string‑related functions follow the source‑to‑destination pattern, e.g., str.split() and str.join() . The latter is a special case where the output (the joined string) appears before the input list.

<code>In [12]: "source to destination".split()
Out[12]: ['source', 'to', 'destination']  # src to dst
In [13]: " ".join(['source', 'to', 'destination'])
Out[13]: 'source to destination'
</code>

Python provides many more string methods than list methods, reflecting its focus on string processing.

<code>In [16]: len([m for m in dir(str) if not m.startswith("__")])
Out[16]: 45
In [17]: len([m for m in dir(list) if not m.startswith("__")])
Out[17]: 11
</code>

4. System date and clock services

Maintaining correct system time is a core OS service, and the same parsing/formatting logic applies to command‑line tools:

<code>$ date -u
$ sudo hwclock -u
2019-05-08 20:19:14.764965+08:00  # str2time, strptime
$ date -d "08 May 2019" +"%c"
Wed 08 May 2019 14:00:00 AM CST  # time2str, strftime
$ date +"%d %B, %Y"
08 May, 2019
</code>

Hope this analysis helps you avoid common pitfalls when using strptime and strftime in Python.

PythonParsingDateTimeformattingstrftimestrptime
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.