簡體   English   中英

更改列表的每個值的特定字符串

[英]Change a specific string on each values of a list

我有一個這樣的列表:

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

使用 Python,我想將列表的每個值更改為"2021/12/31_23:05"以獲得此結果:

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

我怎樣才能做到這一點? 謝謝 !

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)

您可以考慮使用datetime標准庫中的strptimestrptime

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM