In this short post, I’ll show you how to get Python current date using the datetime module.
More specifically, I’ll show you how to get:
- The non-formatted Python current date; and
- The Python current date formatted to different needs
Case-1: get the non-formatted current date in Python
For our 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 that 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 would address this scenario.
Case-2: get the formatted Python current date
Let’s say that you just want to extract the current date, without the ‘time’ element.
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 that syntax in Python, I got the following formatted date:
You’ll notice that we used:
- %d to display the day
- %m to display the month
- %Y to display the year
We just saw 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):
I added some dashes to make the date format more appealing, and this is the code that I got:
import datetime Current_Date_Formatted = datetime.datetime.today().strftime ('%d-%b-%Y') print ('Current Date: ' + str(Current_Date_Formatted))
When running the code:
You can check the Python strftime reference for a comprehensive list of formats that you can apply.
Finally, you may want to check the following source that further explains how to work with system dates in Python.