Are you handling dates in your Python programs? Then you will find the Python datetime module useful. In this tutorial, we will go through a few ways you can use datetime to work with days.
Python datetime is a module that allows manipulating dates as part of your applications. For example, you can use the datetime module to get today’s date, add days to a date, subtract days from a date, and calculate the difference between two dates. These are just some examples of what you can do with datetime using Python.
You will see several examples that will make programming with datetime easier.
How to Get Today’s Date with Python datetime Module
To get today’s date in Python you can use the datetime module. The code to get today’s date is datetime.date.today().
Let’s see how this works in practice:
today = datetime.date.today()
print("Today's date is", today)
The output shows year, month, and day:
Today's date is 2023-03-31
The datetime object returned is of type “datetime.date”:
As you can see, the format of the date is yyyy-mm-dd (year-month-day).
How can you get today’s date in the format dd-mm-yyyy?
To get today’s date in the format dd-mm-yyy you can pass a datetime.date object to the strftime method that also belongs to the datetime module.
Let’s convert today’s date to the day-month-year format:
formatted_date = today.strftime("%d-%m-%Y")
print("Today's date in dd-mm-yyyy format is", formatted_date)
Let’s check the output:
Today's date in dd-mm-yyyy format is 31-03-2023
And here is the type of the variable returned by the strftime method.
The strftime() method returns a string as the name of the method suggests.
How to Get Yesterday’s Date with Python timedelta
In your Python program, you might want to calculate yesterday’s date. This can be useful if you…