Python - "TypeError: 'str' object is not callable",在构建日期格式时(从日期时间开始)



我不明白为什么我在我建立的函数上得到TypeError: 'str' object is not callable。请帮忙吗?解释下…

我有一个元组列表:

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.strptime

中使用适当的格式,您可以通过删除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

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

相关内容

  • 没有找到相关文章