TypeError:“datetime.datetime”对象的描述符“date”不适用于“datetime.date”对象
Posted
技术标签:
【中文标题】TypeError:“datetime.datetime”对象的描述符“date”不适用于“datetime.date”对象【英文标题】:TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object 【发布时间】:2022-01-21 13:43:51 【问题描述】:所以我正在尝试将YYYY-MM-DD
字符串转换为英文格式:WEEKDAY DDth MONTH YEAR
但是,我在将字符串转换为日期格式时遇到问题,我认为该格式是YYYY, MM, DD
。
这是我的代码:
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
我收到TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object
错误,坦率地说,我无法理解。
任何帮助将不胜感激! 干杯
编辑:这是一个使用日历库的工作示例,虽然完全不同,但它可以工作!
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
【问题讨论】:
确切的输入是什么? 实例 2021-12-19 【参考方案1】:如果您使用 datetime 中的 strptime 函数,您将获得对传递给函数的参数进行隐式验证的额外优势。因此,我建议这样做:
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.daydsuffix[d.day] b'
for i in range(1, 32):
d = f'2021-12-i'
print(getHumanDate(d))
【讨论】:
另见Ordinal numbers replacement @MrFuppes 我确实看过它,它非常聪明,但由于必须进行所有计算,它比直接查找效率低。简洁并不总是最好的 是的,命名的 lambdas 也不完全是 PEP8...直接查找另一个可能是最有效的,但可读性也会受到影响,恕我直言,只要您不隐藏查找表本身来自代码的读者 总之,我认为我将在我的数据库中为“人类可读日期”设置一个单独的列,而不是每次加载日期时都这样做......以上是关于TypeError:“datetime.datetime”对象的描述符“date”不适用于“datetime.date”对象的主要内容,如果未能解决你的问题,请参考以下文章
报错解决DateTimeField *** received a naive datetime (***) while time zone support is active
TypeError: 'float' 类型的对象没有 len() & TypeError: 'float' 对象不可迭代