Search code examples
pythonpython-3.xcalendar

I just started to learn Python and I got a little project about Calendar


I need to write a program that will get from the user a date in this format dd/mm/yyyy and will print the day of the week of that date. It has to work for past and future dates. What I did so far isn't working and I don't know why.

Here is what I did so far:

import calendar
import datetime

date = input("Enter a date:")
dd = int(date[:2])
mm = int(date[3:5])
yyyy = int(date[6:9])

print (calendar.weekday(dd, mm, yyyy))

Solution

  • A simpler way to achieve the solution to this problem would be to use datetime's included function strptime(). The documentation can be found here: strptime() function. This function takes in two arguments:

    1. The date string - ex. "12/08/2022"
    2. The format string - ex. "%d/%m/%Y"

    This will return a datetime object which you can use to pass into the calendar.weekday() function. However, it's arguments are in the order: year, month, day which you can find here: weekday() function.

    Then, you can print the output to the terminal by using the calendar.day_name[] array and pass it in the result of the calendar.weekday() function.

    Here is an example code snippet that works regardless of if the user enters leading zeros on single-digit values.

    import calendar
    from datetime import datetime
    
    date = input("Enter a date:")
    date_obj = datetime.strptime(date, '%d/%m/%Y')
    
    print (calendar.day_name[calendar.weekday(date_obj.year, date_obj.month, 
    date_obj.day)])