Reputation: 35
I am having some trouble trying to figure this out. I am currently taking my Python class in college and we are currently working on functions and dates. The instructions are: The user must enter a date separately by: year, month and day. I have read many of the articles similar to the Python Date format, however, everything I try gives me different errors.
Here is my code so far:
import calendar
from datetime import date
from datetime import datetime
from datetime import timedelta
print("Enter the year: ")
year = input()
print("Enter the month: ")
month = input()
print("Enter the day: ")
day = input()
#this is where the input dates should be saved
dateEntered =
#this is somewhat what I'm guessing the output should be
print("The date entered was: " + str(dateEntered))
We have covered things like:
now = datetime.now()
new_date = now + timedelta(days=+3)
print(new_date)
However, I am having trouble figuring out how to store those inputs from the user into a variable that then can be printed out.
Any suggestions will be deeply appreciated!
Thanks!
Upvotes: 1
Views: 935
Reputation: 32596
you can do :
import datetime
print("Enter the year: ")
year = input()
print("Enter the month: ")
month = input()
print("Enter the day: ")
day = input()
dateEntered = datetime.date(int(year), int(month), int(day))
print("The date entered was:", dateEntered)
print("The date entered was:", dateEntered.strftime("%y/%m/%d"))
print("The date entered was:", dateEntered.strftime("%Y/%m/%d"))
print("The month entered was:", dateEntered.month)
Execution :
pi@raspberrypi:~ $ python3 /tmp/p.py
Enter the year:
2021
Enter the month:
1
Enter the day:
31
The date entered was: 2021-01-31
The date entered was: 21/01/31
The date entered was: 2021/01/31
The month entered was: 1
pi@raspberrypi:~ $
Upvotes: 2