Search code examples
pythonpython-dateutil

How to use parser on multiple time objects


I have an list:

list = ['2022-06-01', '2022-02-02']

Now am using parser to convert this to python date object. like this,

from dateutil import parser

def to_date(value):
    for data in value:
        return parser.parse(data)

Above one gives just one output, but i need the output for both the times and also need to convert that to an string like this:

From : June 1, 2022 | To: Feb. 28, 2022

Is that possible with parser ?


Solution

  • You only get one value back from your to_date function because you exit the function in the first loop iteration. You need to introduce an list storing your parsed dates temporary:

    from dateutil import parser
    
    def to_date(date_list):
        parsed_date_list = []
        for date in date_list:
            parsed_date_list.append(parser.parse(date))
        return parsed_date_list
    
    date_list = ['2022-06-01', '2022-02-02']
    res = to_date(date_list)
    

    Or using a list comprehension to keep your code more concise:

    from dateutil import parser
    
    def to_date(date_list):
        return [parser.parse(date) for date in date_list]
    
    date_list = ['2022-06-01', '2022-02-02']
    res = to_date(date_list)
    

    And to format your string, simply use the strftime function as pointed out by kpie in his comment:

    # res = to_date(date_list)
    
    date_format = "%b %d, %Y"
    print(f"From: {res[0].strftime(date_format)} | To: {res[1].strftime(date_format)}")
    

    Do not use list as a variable name. list is a data structure and therefore already in use by the class list.