How to Get the Current Date in Python

In this short guide, you’ll see how to get the current date in Python using the datetime module.

More specifically, you’ll observe 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))

Here is an example of the result if you ran the code on 28-Mar-2021:

Current Date: 2021-03-28 08:49:49.890503

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 explains 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))

And here is the result for our example:

Current Date: 28032021

In the above code, you’ll notice that:

  •  %d  is used to display the day
  • %m is used to display the month
  • %Y is used to display the year

This is just one example of the date format that you may 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 for our example:

Current Date: 28-Mar-2021

You may check the Python strftime reference for a comprehensive list of the formats that you can apply.

You may also want to visit the following source that further explains how to work with system dates in Python.