How to Calculate the Day of the Week for a Given Date in Python (dd-mm-yyyy)

When working with data or building apps, you might find it handy to be able to determine the day of the week for a specific date. This tutorial will guide you through a step-by-step process to write a Python script that calculates the exact day of the week based on a given date in a dd-mm-yyyy format.

Step 1: Import the necessary Python libraries

You’ll need to import Python’s built-in datetime module. The easiest way to utilize this module is to import it to the top of your Python script like this:

Step 2: Define a function to calculate the day of the week

Now you need to define a function that takes the date as an input and returns the day of the week. While providing the date, the format should be dd-mm-yyyy. Then, using the weekday() method of Python’s datetime module, you can get the day of the week as an integer. According to Python’s documentation, the integer 0 represents Monday and 6 represents Sunday. You can create a list of weekdays and then return the calculated day.

Step 3: Test the function with an example date

Finally, let’s test the function by giving it a date in “dd-mm-yyyy” format as input, then printing the returned day:

This will return:

Saturday

The Full Python Code:

Here’s what the final Python script looks like:

Saturday

Conclusion:

As you can see, determining the day of the week in Python for a given date is straightforward. By utilizing Python’s built-in datetime module and defining a simple function, you have now equipped yourself with a useful tool that you can incorporate into a multitude of future projects.