简体   繁体   中英

Change a specific string on each values of a list

I have a list like this:

list = [
    '20211231_2300',
    '20211231_2305',
    '20211231_2310',
    '20211231_2315',
    '20211231_2320',
    '20211231_2325'
]

With Python, I want to change each values of the list by "2021/12/31_23:05" to obtain this result:

[
    '2021/12/31_23:00',
    '2021/12/31_23:05',
    '2021/12/31_23:10',
    '2021/12/31_23:15',
    '2021/12/31_23:20',
    '2021/12/31_23:25'
]

How can I do that? Thank you !

dates = [
    "20211231_2300",
    "20211231_2305",
    "20211231_2310",
    "20211231_2315",
    "20211231_2320",
    "20211231_2325",
]


def format_date(s: str) -> str:
    """assumes correct input format <yyyymmdd_hhmm>"""
    year = s[:4]
    month = s[4:6]
    day = s[6:8]
    hour = s[9:11]
    minute = s[11:]
    return f"{year}/{month}/{day}_{hour}:{minute}"


dates = [format_date(d) for d in dates]
print(dates)

You can consider using strptime and strptime from datetime standard library:

from datetime import datetime

dates = [
    '20211231_2300',
    '20211231_2305',
    '20211231_2310',
    '20211231_2315',
    '20211231_2320',
    '20211231_2325'
]

fmt = [datetime.strptime(date, "%Y%m%d_%H%M").strftime("%Y/%m/%d_%H:%M") for date in dates] 

print(fmt) # prints: ['2021/12/31_23:00', '2021/12/31_23:05', '2021/12/31_23:10', '2021/12/31_23:15', '2021/12/31_23:20', '2021/12/31_23:25']

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