In Python, we can easily format dates and datetime objects with the strftime() function. For example, to format a date as YYYY-MM-DD, pass “%Y-%m-%d” to strftime().
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime("%Y-%m-%d"))
#Output:
2022-03-12
If you want to create a string that is separated by slashes (“/”) instead of dashes (“-“), pass “%Y/%m/%d” to strftime().
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime("%Y/%m/%d"))
#Output:
2022/03/12
When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display the current date in a particular format.
The Python strftime() function is very useful when working with date and datetime variables. strftime() accepts a string representing the format of a date and returns the date as a string in the given format.
We can use strftime() to easily format a date using codes for the day, month or year.
For example, if we want to format a date in the format yyyymmdd, we can do so by passing “%Y” for year, “%m” for month, and “%d” for day to strftime() in the order you want.
Below is a simple example of how to format and print a date with the format yyyy-mm-dd in Python with strftime().
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime("%Y-%m-%d"))
#Output:
2022-03-12
How to Change Date Formats in Python with strftime()
We can use strftime() to format dates and change the date format easily of a date or datetime object.
For example, if you want to change the date format to MM/DD/YYYY, you can pass “%m/%d/%Y” to strftime().
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime("%m/%d/%Y"))
#Output:
03/12/2022
Another useful code for formatting dates is the month name code “%B”. “%B” gets the month name of a date.
We can format a date like “Month Name DD, YYYY” easily by passing “%B %d, %Y” to strftime().
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime("%B %d, %Y"))
#Output:
March 12, 2022
Hopefully this article has been useful for you to learn how to learn how to format dates in Python with strftime().