Getting the Day of a Date Using Python

Getting the Day of a Date Using Python

ECX 30 Days of Code and Design

Day 19

Task

Write a function that takes in a date as input, and returns what day of the week it is.

  • The input date can be in any convenient format (whether a "ddmmyy" string, a series of integers, etc.)
  • Your function must work for both future and past dates.
  • Exception handling (or type checking) is necessary.

My Approach

First, we import the datetime module which we would to access the datetime() and strfttime() functions. Next, we define the function, day_of_the_date(), which we would use to find the given day of the day inputted by the user. The user is asked to input the year, month, and day of the month which s/he wants to know the day of the week. The values gotten from the user are passed as arguments to the datetime() function, and the strftime() function is used to print out the date. %Y, %m, %d, and A% implies year, month, day of the month, and day of the week respectively. The code is wrapped in a try except block to handle ValueError. Finally, we call the function.

import datetime             # For datetime(), strftime()


def day_of_the_date():
    """Prints out the day of a given date."""
    try:
        print(' Get the day name of a particular date '.center(45, '*'))
        year = int(input('Year; 2011: '))
        month = int(input('Month; Jan - 1, Feb - 2 ...: '))
        day = int(input('Day; 1 - (28...31): '))

        date = datetime.datetime(year, month, day)
        print(date.strftime('%Y-%m-%d') + ' is a ' + date.strftime('%A'))
        return date.strftime('%A')

        # To take care of a case where the user inputs a wrong month/day number
    except ValueError:
        print('Invalid! Please, input the correct month/day range.')


day_of_the_date()

Output

If we input 8 May 2022 (08-05-2022), we get;

*** Get the day name of a particular date ***
Year; 2011: 2022
Month; Jan - 1, Feb - 2 ...: 05
Day; 1 - (28...31): 08
2022-05-08 is a Sunday

Run the code on Replit.