Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
So I am trying to convert a
YYYY-MM-DD
string into a English format as:
WEEKDAY DDth MONTH YEAR
However I am having issue converting the string into a date format which I believe is
YYYY, MM, DD
.
Here is my code:
from datetime import datetime, date
[...]
def getHumanDate(rawdate):
the_date = date(int(rawdate[0:4]), int(rawdate[6:7]), int(rawdate[9:10]))
weekday = (datetime.date(the_date).strftime('%A'))
month = (datetime.date(the_date).strftime('%B'))
year = int(rawdate[0:4])
day = int(rawdate[9:10])
english = weekday + " " + day + "th of " + month + " " + year
return english
I am getting a TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object
error which I frankly can't wrap my head around.
Any help would be appreciated!
Cheers
Edit: Here is a working example using the Calendar library, although completely different, it works!
import calendar
[...]
def getHumanDate(rawdate):
int_year = int(rawdate[0:4])
int_month = int(rawdate[6:7])
int_day = int(rawdate[9:10])
week_days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
months=["", "January","February","March","April","May","June","July", "August","September","October","November","December"]
weekday = calendar.weekday(int_year, int_month, int_day)
english = week_days[weekday] + " " + str(int_day) + "th of " + months[int_month] + " " + str(int_year)
return English
–
If you use the strptime function from datetime you get the added advantage of implicit validation of the parameter being pass to your function. Therefore, I suggest this:
from datetime import datetime
dsuffix = [None, 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st']
def getHumanDate(date): # parameter is expect in ISO format YYYY-MM-DD
d = datetime.strptime(date, '%Y-%m-%d')
a = datetime.strftime(d, '%A')
b = datetime.strftime(d, '%B %Y')
return f'{a} {d.day}{dsuffix[d.day]} {b}'
for i in range(1, 32):
d = f'2021-12-{i}'
print(getHumanDate(d))
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.