Python 巨蟒;类型错误:';str';对象不可调用";,生成日期格式时(从日期时间)

Python 巨蟒;类型错误:';str';对象不可调用";,生成日期格式时(从日期时间),python,function,datetime,typeerror,Python,Function,Datetime,Typeerror,我不明白为什么我得到了TypeError:“str”对象不能在我构建的函数上调用。请帮忙?下面的解释 我有一个元组列表: date_list = [ (0, ' Thursday - 18 February 2021'), (40, ' Friday - 19 February 2021'), (68, ' Saturday - 20 February 2021'), (129, ' Sunday - 21 February 2021'), (190, ' Monday -

我不明白为什么我得到了
TypeError:“str”对象不能在我构建的函数上调用。请帮忙?下面的解释

我有一个元组列表:

date_list = [
 (0, '  Thursday - 18 February 2021'),
 (40, '  Friday - 19 February 2021'),
 (68, '  Saturday - 20 February 2021'),
 (129, '  Sunday - 21 February 2021'),
 (190, '  Monday - 22 February 2021'),
 (260, '  Tuesday - 23 February 2021'),
 (300, '  Wednesday - 24 February 2021'),
 (337, '  Thursday - 25 February 2021'),
 (377, '  Friday - 26 February 2021'),
 (402, '  Saturday - 27 February 2021'),
 (463, '  Sunday - 28 February 2021'),
 (524, '  Monday - 01 March 2021'),
 (591, '  Tuesday - 02 March 2021'),
 (631, '  Wednesday - 03 March 2021'),
 (668, '  Thursday - 04 March 2021')
]
忽略每个元组索引0处的数字,因为它们不是问题的一部分(出于好奇,它们表示元组索引1处元素的列表索引号,从另一个列表中选取)

现在,我有以下功能:

def date_update(date_list):

    print("\ndate_update():")

    updated_dates = []

    # months dictionary, to swap word for number
    months = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}

    # pattern for regex on day and year
    day_pattern = re.compile(r'(\d{2})')
    year_pattern = re.compile(r'(\d{4})')

    # extract day and year
    for true_index, date in date_list:
        day_extracts = int(re.search(day_pattern, date).group())
        year_extracts = int(re.search(year_pattern, date).group())

        # identify month
        for month in months:
            if month in date:
                month_extracts = int(months[month])
            else:
                pass
        
        date_format = date(year_extracts, month_extracts, day_extracts)
        
        return date_format

有人能看出哪里出了问题吗?

如果您使用适当的格式在
datetime.strtime中输入,您可以通过删除regex和dict操作来简化代码

from datetime import strptime

for idx, str_date in date_list:
    print(datetime.strptime(str_date.strip(), "%A - %d %B %Y"))

2021-02-18 00:00:00
2021-02-19 00:00:00
2021-02-20 00:00:00
2021-02-21 00:00:00
2021-02-22 00:00:00
2021-02-23 00:00:00
2021-02-24 00:00:00
2021-02-25 00:00:00
2021-02-26 00:00:00
2021-02-27 00:00:00
2021-02-28 00:00:00
2021-03-01 00:00:00
2021-03-02 00:00:00
2021-03-03 00:00:00
2021-03-04 00:00:00

不打印日期,您只需将其存储在列表中,并在需要时在代码中使用它。

您的循环是
对于true\u索引,date\u列表中的日期:
接下来的几行您将编写
date\u format=date(year\u extracts,month\u extracts,day\u extracts)
。date显然是一个字符串,你怎么称呼它?可能您想在这里使用
datetime.date
,请尝试为变量使用其他名称,或者使用
import datetime
datetime.date(…)
而不是
from datetime import date
该死,没错!!!thanksdateutil的解析器可以增加更多的便利性(如果效率不是问题的话)