Hi
I have two questions about dates in python:
Thanks.
1) when i input e.g. 18-02-1992, i expect to get the same, but instead, i get 1992-02-18. How come and how to get 18-02-1954?
import datetime
dt1 = str(input("Input date (dd-mm-jjjj): "))
dt2=datetime.datetime.strptime(dt1,"%d-%m-%Y").date()
print(dt2) # i get 1992-02-18
2) I want the weekday of the inputted date: the first way works (for 18-02-1992 i get Tuesday), but the second way gives " import datetime
dt1 = str(input("Input date (dd-mm-jjjj): "))
dt2=datetime.datetime.strptime(dt1,"%d-%m-%Y").date()
print(dt2)
print(("De dag van de week voor {} is {}: ").format(dt2,dt2.strftime('%A'))) # this works
print(("De dag van de week voor {} is {}: ").format(dt2.strftime('%d-%B-%Y'),dt2.weekday)) # this doesn't work
Tuhin PaulPosted Mar 20, 2023, 12:10 AM
For Question 1:
I can suggest some minor improvements for readability and clarity:
I've added a variable to store the input date string for readability, and also used an f-string to make the print statement more clear
Tuhin PaulPosted Mar 20, 2023, 12:12 AM
For Question 2:
Valerie MeunierPosted Mar 19, 2023, 9:59 PM
Thanks again. Again, stupid error ...
Abhijeet JadhavPosted Mar 19, 2023, 7:23 PM
Try this code :
Valerie MeunierPosted Mar 19, 2023, 10:33 AM
Hi, thanks. The first problem is solved.
For the second, i tried this:
import datetime
dt=datetime. datetime.strptime(input("Input date (dd-mm-jjjj): "),"%d-%m-%Y")
print(f"Weekday of {{dt.strftime('%d-%m-%Y')}} is {dt.weekday}: ")
But this gives the same error, although dt is of type datetime ...
Abhijeet JadhavPosted Mar 18, 2023, 10:47 PM
For Question 2 :
Try this to get the weekday number :
Abhijeet JadhavPosted Mar 18, 2023, 10:43 PM
Answer to the Question :1 )
In Python, the default date format is YYYY-MM-DD (Year-Month-Day). That's why when you input "18-02-1992", Python assumes that the date is in DD-MM-YYYY format and converts it to YYYY-MM-DD format.
To get the desired format of "18-02-1992", you need to explicitly format the date using the strftime() method. Here's an example code snippet that shows how to achieve this: