-1

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 !

JonSG
  • 10,542
  • 2
  • 25
  • 36
Thurro
  • 41
  • 4
  • 1
    Do you know how you can do it for a single string? – mkrieger1 Jan 06 '22 at 16:45
  • 1
    You may find [this stackoverflow question](https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format) helpful – Ewan Brown Jan 06 '22 at 16:46
  • 1
    You might not want to use type names as variable names. – JonSG Jan 06 '22 at 16:52
  • 1
    Hi and welcome to SO. It is important for the community that you *also* demonstrate that you are working to solve your issue. The best way to do that in my opinion is to include the **text** based version of the source code you have so far, even if it is not working quite right. – JonSG Jan 06 '22 at 17:00

2 Answers2

1
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)
luku
  • 63
  • 5
  • 1
    Consider looking into the "datetime" lib - this string solution shouldn't be the solution of choice. – luku Jan 06 '22 at 17:13
1

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']
Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40