【问题标题】:Python - "TypeError: 'str' object is not callable", when building a date format (from datetime)Python - 构建日期格式时(来自日期时间)“TypeError:'str'对象不可调用”
【发布时间】:2021-05-21 12:54:24
【问题描述】:

我不明白我为什么在我构建的函数上得到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

谁能看出问题所在?

【问题讨论】:

  • 你的循环是for true_index, date in date_list:,接下来几行你写date_format = date(year_extracts, month_extracts, day_extracts)。 date 显然在这里是一个字符串,你怎么称呼它?您可能想在这里使用datetime.date,尝试为您的变量使用其他名称或使用import datetimedatetime.date(...) 而不是from datetime import date
  • 该死的没错!!!谢谢

标签: python function datetime typeerror


【解决方案1】:

如果您在datetime.strptime 中使用正确的格式,则可以通过删除正则表达式和字典操作来简化代码

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

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

【讨论】:

  • dateutil 的解析器可以增加更多便利(如果效率不是问题)
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 2017-05-26
  • 2019-12-20
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多