[英]TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object
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
.所以我试图将
YYYY-MM-DD
字符串转换为英文格式: WEEKDAY DDth MONTH YEAR
但是我在将字符串转换为我认为是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.我收到一个
TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object
错误,坦率地说我无法理解。
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.如果您从 datetime 使用 strptime function,您将获得对传递给 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.