How to Get the Current Date in Python

Rayven Esplanada Feb 02, 2024
How to Get the Current Date in Python

This tutorial demonstrates how to get the current date in Python.

Use the datetime Module to Get the Current Date in Python

The datetime module has utility functions specifically for date and time manipulations in Python. Within the module it has an object of the same name that has the function today() that returns the current date and time with the default date-time format.

As an example, import the datetime module and directly print the output of datetime.today().

from datetime import datetime

print(datetime.today())

Output:

2021-03-09 15:05:55.020360

To modify the default format for the datetime, use the strftime format and call the strftime() method that’s also built-in within the datetime module.

For example, to display the current date without the time, the format for that is %Y-%m-%d.

from datetime import datetime

print(datetime.today().strftime("%Y-%m-%d"))

Output:

2021-03-09

To include the time but without the seconds and milliseconds, the format for that would be %Y-%m-%d %H-%M.

from datetime import datetime

print(datetime.today().strftime("%Y-%m-%d %H:%M"))

Output:

2021-03-09 15:05

Another format would be to include the day of the week. In this example, we will use the month’s actual name.

from datetime import datetime

print(datetime.today().strftime("%A, %B %d, %Y %H:%M:%S"))

Output:

Tuesday, March 09, 2021 15:05:55

In summary, the datetime module can be used to get the current date by using the function today(). To extensively modify the default date format, strftime formatting can be followed and applied by using the strftime() function.

Rayven Esplanada avatar Rayven Esplanada avatar

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.

LinkedIn

Related Article - Python DateTime