How to format dates in Python3. Comparison of strftime, format, and... | by Adam Oudad | Towards Data Science

You have probably used Python’s formatting syntax before. But how do you format a date? With datetime objects, you can use %Y, %m, %d to display respectively, the year, the month and the day of an object, in numerical form (that is, March will be replaced by the number "03").
Python has several syntax for formatting strings. So that each of these lines will produce the same output.
Output:
2020年08月04日
These lines produce the standard for Japanese dates. 年 means year, 月 means month, 日 means day.
Let’s look at each syntax.
strftime is a function which dates back to early python days. Its naming is quite cryptic, but is nonetheless most used for its closeness to what we would expect for date formatting: a method whose job is to format things.
It does that very well. But the syntax is arguably clumsy. strftime is not the easiest word to type. Besides, what if we need to format several dates inside the same string?
Note, however, the existence of .strptime, which is the inverse transformation of .strftime. In English, these names would translate to "String Parse Time" and "String Format Time".
.format is a method of the str class, used to format a string containing formatting syntax. What we call replacement field is marked by accolades {}. It is used to mark places where parameters passed to the method will be inserted. A number inside accolades {1} serves to select the parameter. Be careful that it starts at 0, so the first passed parameter will be inserted with {0}. Here is an example to summarize:
"The {0} parameter. The {2} parameter. The {1} parameter.".format("first", "second", "third")
Notice you can order or replicate the use of replacement fields {} as necessary. You can also insert named parameters
"Cut the {first}. Wash the {second}. Prepare the {third}.".format(first="onions", second="carrots", third="salad")
For datetime objects, we have additional formatting. For example {0:%Y} will insert the year of the date in first positional argument, which is expected to be a datetime object. Hence, you can see why these two lines will produce the same output.
"{:%Y年%m月%d日}".format(datetime.today())"{0:%Y}{1}{0:%m}{2}{0:%d}{3}".format(datetime.today(), "年", "月", "日")
The first one puts everything inside the replacement field {} , whereas the second one separates it into several inserted parameters. It depends on the situation to choose which one will be more readable.
Lesser known due to its recent introduction in python3.6, the f-String or String interpolation is a powerful and concise way to format strings. With the f"" syntax, you can directly put variable names alongside formatting syntax. For example.
age = 25print(f"So you are {age} years-old?")
We can even write function calls inside! So now, you should understand how we got the same output as before with:
f"{datetime.today():%Y年%m月%d日}"
Even though .strftime is still widely used, it is the less readable in my opinion, as the other syntaxes are closer to what we would expect of a pythonic code. The main reason behind this is the formatting operation is effectively performed on the str object, not the datetime object. So I would recommend you to prefer .format and f"" which are more concise. F-strings can also be used for debugging. For example print(f"{a=}") will print out a= followed by the actual value of a. Check out the documentation for more.
Originally published at https://adamoudad.github.io on August 4, 2020.