8 Ways of Using Python Datetime to Work With Days

Claudio Sabato
7 min readApr 1, 2023

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.

Let’s start!

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:

import datetime

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”:

print(type(today))

[output]
<class '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.

print(type(formatted_date))

[output]
<class 'str'>

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 want your program to collect data or stats for the day before the execution of the program.

To subtract one day from today’s date you can use datetime.timedelta(). You have to pass the argument “days” to datetime.timedelta() and set the value of the argument “days” to 1.

You can pass different types of arguments to datetime.timedelta() depending on the delta you want to calculate:

  • microseconds
  • milliseconds
  • seconds
  • minutes
  • hours
  • days
  • weeks
import datetime

today = datetime.date.today()
print("Today's date is", today)

yesterday = today - datetime.timedelta(days=1)
print("Yesterday's date is", yesterday)

Let’s print today’s date first to confirm that yesterday’s date is correct.

Today's date is 2023-03-31
Yesterday's date is 2023-03-30

Yesterday’s date is correct!

How Do You Subtract Days From a Date in Python?

This is pretty much the same concept we covered in the previous section.

To subtract days from a date in Python you can calculate the initial date using datetime.date(), then use datetime.timedelta() to get the number of days you want to subtract.

Previously we have used datetime.date to calculate today’s date. Now, let’s use datetime.date to get back an object for a date we specify.

Imagine you are creating a program to collect some stats for a given day.

stats_date = datetime.date(2023, 6, 25)
print(stats_date)

[output]
2023-06-25

Now that we have a date object let’s subtract 7 days from this date.

stats_date_minus_7days = stats_date - datetime.timedelta(days=7) 
print(stats_date_minus_7days)

[output]
2023-06-18

The output is correct. You can also pass the argument weeks to datetime.timedelta.

stats_date_minus_7days = stats_date - datetime.timedelta(weeks=1)
print(stats_date_minus_7days)

[output]
2023-06-18

As expected the output is the same when passing days=7 or weeks=1 as the argument.

How Do You Add 1 Month to a Date in Python?

In this section, we will see how to add 1 month to a given date using Python.

To add 1 month or any number of months to a date in Python you can use dateutil.relativedelta part of the dateutil module.

To install dateutil run the following command:

pip install python-dateutil

If the dateutil module is not available in your Python environment, you will see the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'dateutil'

Now let’s see how to add one month to a date in Python using dateutil.

import datetime
from dateutil.relativedelta import relativedelta

stats_date = datetime.date(2023, 6, 25)
print("The initial date is", stats_date)

date_plus_1month = stats_date + relativedelta(months=1)
print("The initial date plus one month is", date_plus_1month)

Let’s confirm the date we have calculated by adding one month to the original date is correct.

The initial date is 2023-06-25
The initial date plus one month is 2023-07-25

How Do You Find the Difference Between Two Dates in Python?

A common logic you might have to implement in a Python program is to calculate the number of days between two dates.

To calculate the difference in number of days between two dates in Python you can subtract one date object from another. This will give you the difference between the two dates that is represented using a datetime.timedelta object.

Here is an example of how to calculate the number of days between two dates using Python.

date1 = datetime.date(2023, 6, 25)
date2 = datetime.date(2023, 6, 5)
difference = date1 - date2
print(type(difference))

[output]
<class 'datetime.timedelta'>

This shows that the difference between the two dates is a datetime.timedelta object.

Now, let’s see the value of this timedelta object in days.

print(difference.days)

[output]
20

The days between the two dates are correct!

Here is what happens if we reverse the order of the dates when calculating the difference.

difference = date2 - date1
print(difference.days)

[output]
-20

The difference in days is negative considering that we are subtracting (2023, 6, 25) from (2023, 6, 5).

It’s possible that in your program you might only want to know the absolute value of the difference.

print(abs(difference.days))

[output]
20

Below you can see the attributes of a datetime.timedelta object. You can obtain them using Python’s dir() built-in function.

print(dir(difference))

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']

You can see that some of the attributes are related to time, for example, days, microseconds, and seconds.

Calculate the Start of the Month in Python

To calculate the start of a month in Python based on a date you can use the date.replace() method and replace the day of the given date with day number 1 (the first day of the month).

date1 = datetime.date(2023, 6, 25)
start_of_month_date = date1.replace(day=1)
print("The first day of the month is", start_of_month_date)

The beginning of the month is correct:

The first day of the month is 2023-06-01

How to Get the First Day of the Next Month in Python

The first thing to do to get the first day of the following month is to first get the following month from the date object. To do that we create the function get_next_month().

We can then use date.replace() to replace the day with the number 1 and the month with the next month returned by the get_next_month() function.

import datetime

def get_next_month(month):
if month == 12:
next_month = 1
else:
next_month = month + 1

return next_month

current_date = datetime.date(2023, 6, 25)
print("The current date is", current_date)

current_month = current_date.month
print("The current month is", current_month)

next_month = get_next_month(current_month)
print("The next month is", next_month)

first_day_of_next_month = current_date.replace(day=1, month=next_month)
print("The first day of the next month is", first_day_of_next_month)

Here is the output of the Python program:

The current date is 2023-06-25
The current month is 6
The next month is 7
The first day of the next month is 2023-07-01

The output is correct.

Calculate the End of the Month in Python

To calculate the end of the month in Python you can use a function that calculates the first day of the next month and then subtract one day from that date.

Let’s start by creating a function that calculates the first day of the next month based on the code we created in the previous section.

The function is called get_first_day_of_next_month() and as you can see in the code below it calls the function get_next_month() we had previously created.

import datetime

def get_next_month(month):
if month == 12:
next_month = 1
else:
next_month = month + 1

return next_month

def get_first_day_of_next_month(date):
current_month = date.month
next_month = get_next_month(current_month)
first_day_of_next_month = date.replace(day=1, month=next_month)
return first_day_of_next_month

current_date = datetime.date(2023, 6, 25)
print("The current date is", current_date)

first_day_of_next_month = get_first_day_of_next_month(current_date)
end_of_month = first_day_of_next_month - datetime.timedelta(days=1)
print("The end of the month is", end_of_month)

After calculating the next month’s first day, we subtract one day from it using datetime.timedelta(). This gives us the end of the month (the last day of the current month).

The current date is 2023-06-25
The end of the month is 2023-06-30

Conclusion

In this Python tutorial about working with days using Python datetime, we have covered several use cases that will help you with programs you will create in the future.

We have seen how to use Python’s datetime module to:

  • Get today’s date
  • Get yesterday’s date
  • Subtract days from a date
  • Add days/months to a date
  • Find the number of days between two given dates
  • Calculate the start of the month, the end of the month, and the beginning of the following month.

Related article: in this tutorial we have used a few Python functions. To get a more in-depth understanding of how functions work, have a look at the Codefather tutorial about Python functions.

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.