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:
1 |
import datetime |
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.
1 2 3 4 |
def findDay(date): day, month, year = (int(i) for i in date.split('-')) born = datetime.datetime(year, month, day) return (born.strftime("%A")) |
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:
1 2 3 |
date = '30-08-1997' day = findDay(date) print(day) |
This will return:
Saturday
The Full Python Code:
Here’s what the final Python script looks like:
1 2 3 4 5 6 7 8 9 10 |
import datetime def findDay(date): day, month, year = (int(i) for i in date.split('-')) born = datetime.datetime(year, month, day) return (born.strftime("%A")) date = '30-08-1997' day = findDay(date) print(day) |
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.