简体   繁体   中英

Python - “TypeError: 'str' object is not callable”, when building a date format (from datetime)

I don't understand why I get TypeError: 'str' object is not callable on a function I've built. Please, help? Explanation below...

I have a list of tuples:

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')
]

Ignore the numbers at index 0 of each tuple, because they aren't part of the problem (for the curious, they represent the list index number of the element at index 1 of tuples, picked from another list).

Now, I have the following function:

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

Can anyone see what's wrong?

You can simplify your code by removing regex and dict operations, if you use proper format to in 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

Instead of printing the dates, you can simply store it in a list and use it when needed in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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