Home > Back-end >  Convert date format in python when zipping two lists
Convert date format in python when zipping two lists

Time:02-16

Lets say i have two lists:

list1 = ['2022-01-01','2022-02-02']
list2 = ['2021-03-03','2021-04-04']

Now i want to combine both the list like list1[0] matches with list2[0] so the expected output woud be like:

output = [['2022-01-01','2021-03-03'],['2022-02-02','2021-04-04']]

I have achived this using this code:

output = [list(a) for a in zip(list1 , list2)]

It works perfectly, but the problem is i need to convert the date into pythons date form. As now, the date is in normal local format but i need convert that into pythons datetime.datetime format while zipping. So how to do that ?

CodePudding user response:

You could use the method datetime.strptime. Here are the formatting codes.

You could do it like this:

from datetime import datetime


list1 = ['2022-01-01', '2022-02-02']
list2 = ['2021-03-03', '2021-04-04']
date_formst = '%Y-%m-%d'

output = [
    list(a)
    for a in zip(
        [datetime.strptime(d, date_formst) for d in list1],
        [datetime.strptime(d, date_formst) for d in list2]
    )
]

print(output)

The output would be:

[[datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2021, 3, 3, 0, 0)], [datetime.datetime(2022, 2, 2, 0, 0), datetime.datetime(2021, 4, 4, 0, 0)]]

CodePudding user response:

You use another list comprehension:

import datetime as dt

list1 = ['2022-01-01', '2022-02-02']
list2 = ['2021-03-03', '2021-04-04']

output = [
    [dt.datetime.strptime(dte, '%Y-%m-%d') for dte in a]
    for a in zip(list1, list2)
]
print(output)

Out:

[[datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2021, 3, 3, 0, 0)], [datetime.datetime(2022, 2, 2, 0, 0), datetime.datetime(2021, 4, 4, 0, 0)]]

CodePudding user response:

There are many ways to achieve this. Here's one:

from datetime import datetime

FORMAT = '%Y-%m-%d'

list1 = ['2022-01-01','2022-02-02']
list2 = ['2021-03-03','2021-04-04']

def to_datetime(values):
    return [datetime.strptime(v, FORMAT) for v in values]

output = list(map(to_datetime, zip(list1, list2)))

print(output)
  • Related