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

Time:08-13

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))

CodePudding user response:

You got the slice wrong for the year, it should be 6:10 to get 4 digits.

But instead of slicing specific digits, you can use split() to separate the input string at / delimiters.

You have the arguments to calendar.weekday() in the wrong order.

date = input("Enter a date:")
dd, mm, yyyy = map(int, date.split('/'))

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

If you want the name of the day instead of a number, use calendar.day_name to convert the number to a name.

print(calendar.day_name[calendar.weekday(yyyy, mm, dd)])

CodePudding user response:

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)])
  • Related