繁体   English   中英

TypeError: 'datetime.datetime' 对象的描述符 'date' 不适用于 'datetime.date' object

[英]TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'datetime.date' object

所以我试图将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

如果您从 datetime 使用 strptime function,您将获得对传递给 function 的参数进行隐式验证的额外优势。 因此,我建议这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM