Working with dates and times is a common task in Python programming, and it’s important to know how to get the current date. In this tutorial, we will learn how to obtain the current date using the Python programming language and utilizing the built-in datetime
module.
Step 1: Import the datetime module
First, we need to import the datetime
module. The datetime module supplies classes for manipulating dates and times, and has an object called date
that provides various methods and attributes, including a method to fetch the current date.
To import the datetime module, simply add the following line of code:
1 |
import datetime |
Step 2: Get the current date
Now, to get the current date, we will use the date.today()
method. The today()
method returns the current local date as a date object.
Here’s how to get the current date object:
1 |
current_date = datetime.date.today() |
Step 3: Print the current date
Finally, let’s print the current date to the output in a human-readable format. To do this, we will use the strftime()
method, which formats the date object as a string.
Here’s how to print the current date in a formatted string:
1 2 |
formatted_today = current_date.strftime("%Y-%m-%d") print("Today's date is:", formatted_today) |
The %Y-%m-%d
in strftime()
represents the format in which we want to display the date. In this case, it will display the date in the popular YYYY-MM-DD format.
The full code to get the current date is given below:
1 2 3 4 5 |
import datetime current_date = datetime.date.today() formatted_today = current_date.strftime("%Y-%m-%d") print("Today's date is:", formatted_today) |
The output for this code would look like:
Today's date is: 2023-02-20
Note that the output will vary according to the date when the script is executed.
Conclusion
In this tutorial, we learned how to get the current date in Python using the built-in datetime module. This is a fundamental skill for working with dates and times, and understanding how to import the datetime module and use its various methods is essential for Python developers.