[英]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:使用 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'
]
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:您可以考虑使用datetime
标准库中的strptime
和strptime
:
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.