Working with dates is a common scenario when creating Python applications. Fortunately, Python provides the datetime module which makes it quite easy to get a date and format it as you may need, such as in the DD/MM/YYYY format. In this tutorial, we will walk through the steps for how to print a date in this format.
Import necessary libraries
Before we start working with dates, we need to import the datetime library in Python. The datetime module supplies classes to work with date and time.
1 |
import datetime |
Obtain the current date
Let’s now obtain the current date. We can do this by calling the datetime.now() function from the datetime module.
1 |
current_date = datetime.datetime.now() |
Printing the date in DD/MM/YYYY format
The date obtained above is in a default format provided by the python. However, we can format this date in DD/MM/YYYY by calling the strftime function on the date object.
1 2 |
formatted_date = current_date.strftime("%d/%m/%Y") print(formatted_date) |
Coding Explanation
The strftime function is used to format date and time in Python. We pass a format string to this function to specify the output string format. Here are some common directives used in the format string:
- %d: Day of the month as a zero-padded decimal number
- %m: Month as a zero-padded decimal number
- %Y: Year with century as a decimal number
Find out more about the strftime function and its directives here.
The Full Code
1 2 3 4 5 6 7 8 |
import datetime # Get current date current_date = datetime.datetime.now() # Format and print date formatted_date = current_date.strftime("%d/%m/%Y") print(formatted_date) |
Output
03/05/2022
Note: The output date will vary based on the date you run this code.
Conclusion
Python’s datetime module provides functionality to work with dates and times. This tutorial demonstrated how to get the current date and print it in DD/MM/YYYY format. Remember, the strftime() method is at your disposal for formatting date and time in Python, and you can use a variety of directives to display date and time exactly the way you need.