In this short guide, I’ll show you how to get the current date in Python using the datetime module.
More specifically, I’ll show you how to get:
- The non-formatted current date; and
- The formatted current date across different scenarios
Get the Non-Formatted Current Date in Python
For the first case, simply apply the following syntax to get the current date in Python:
import datetime Current_Date = datetime.datetime.today() print ('Current Date: ' + str(Current_Date))
When I ran the above code in Python, I got the following result:
As you can see, both the current date and time are displayed when running the code. In some cases, you may just want to display the date without the ‘time’ portion.
So how would you do that?
The second case below would address this scenario.
Get the Formatted Current Date
Let’s say that you just want to extract the current date, without the ‘time’ portion.
For example, you may want to display the date as: ddmmyyyy, where:
- dd would represent the day in the month
- mm would represent the month
- yyyy would represent the year
Here is the Python code that you can apply:
import datetime Current_Date_Formatted = datetime.datetime.today().strftime ('%d%m%Y') print ('Current Date: ' + str(Current_Date_Formatted))
Once I ran the above syntax in Python, I got the following formatted date:
You’ll notice that I used:
- %d to display the day
- %m to display the month
- %Y to display the year
This is just one example of the date format that you can apply in Python. You can easily apply different date formats by changing the parameters within the strftime brackets.
For instance, to present the month in characters, rather than in digits, you can use %b within the strftime brackets (instead of %m):
strftime ('%d-%b-%Y')
So the complete Python code would look like this:
import datetime Current_Date_Formatted = datetime.datetime.today().strftime ('%d-%b-%Y') print ('Current Date: ' + str(Current_Date_Formatted))
And this is the result that I got when running the code:
You can check the Python strftime reference for a comprehensive list of the formats that you can apply.
You may also want to check the following source that further explains how to work with system dates in Python.