How to get the current date in Python

Published on Aug. 22, 2023, 12:15 p.m.

To get the current date in Python, you can use the datetime module. Here’s an example of how to do this:

from datetime import datetime

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

This will print out the current date in the default date format for your system.

Alternatively, you can use the date class from the datetime module to create a date object for a specific date. Here’s an example:

from datetime import date

my_date = date(2023, 3, 25)
print(my_date)

This will create a date object for the date March 25, 2023, and print it out.

You can also specify the format of the date string and parse it to create a date object using the strptime() method. Here’s an example:

from datetime import datetime

date_str = '2023-03-25'
my_date = datetime.strptime(date_str, '%Y-%m-%d').date()
print(my_date)

This will create a date object for the date March 25, 2023, and print it out.

Tags:

related content