Ways to get today’s date in Python

This tutorial will demonstrate how to get today’s date in Python.

Python provides the standard datetime module that can create objects that can store and manipulate date and time values. Other libraries like calendar, and dateutil can also work with objects of the datetime class.

Using the datetime.date.today() function

We will use the today() function from the datetime module.

For example,

# Get Today's Date in Python

import datetime
today_date = datetime.date.today()
print(today_date)

# Output: 2023-03-23

The final value is stored in the datetime.date object.

We can also get the result in the form of a string. For this, we can use the datetime.strftime() function. This function returns the string with the date and time in the specified format.

See the code below.

# Get Today's Date in Python

import datetime
today_date = datetime.date.today()
diff_format = today_date.strftime('%d-%m-%Y')
print(diff_format)

# Output: 23-03-2023

We will see the use of this function in the method below.

Using the datetime.now() function

This function returns the current date and time based on the provided timezone. It uses the Greenwich Meridian timezone by default.

To get today’s date in Python,

  • Get the current date and time using the datetime.now() function.
  • Extract today’s date from this using the datetime.strftime() function.

See the code below.

# Get Today's Date in Python

import datetime
today_date = datetime.datetime.now()
diff_format = today_date.strftime('%d-%m-%Y')
print(diff_format)

# Output: 23-03-2023

Alternative approach: The arrow library

Many different libraries work with datetime objects in Python. This can lead to a lot of confusion at times. The arrow library was built as an alternative to the traditional datetime module and provides many simple functionalities built under the same roof.

The current date and time can be returned using the arrow.now() function. We can get the date from this object using the format() function.

See the code below.

# Get Today's Date in Python

import arrow
today_date = arrow.now().format('D-M-YYYY')
print(today_date)

# Output: 23-03-2023

To conclude…

We discuss several ways to get today’s date in Python. The use of the datetime module to achieve the same was explained in detail. An additional approach using the arrow library is also demonstrated. Either of the methods can fulfill the requirement of getting today’s date.

Explore more from this category at Python Date and Time. Alternatively, search and view other topics at All Tutorials.