-1

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 ?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
sixovov947
  • 205
  • 1
  • 7
  • 1
    What is `parser`? Are you aware that `return` exits the function? Do you know how to do a list comprehension or something similar, like `[parser.parse(s) for s in value]`? – wjandrea Feb 16 '22 at 03:26
  • Sorry am an newbie, parser is from dateutil – sixovov947 Feb 16 '22 at 03:28
  • I would recommend using `datetime.strptime` and `strftime`. They are standard and most experienced python programmers will be familiar. – kpie Feb 16 '22 at 03:38

2 Answers2

0

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.

Thomas
  • 8,357
  • 15
  • 45
  • 81
0

You can use the standard datetime library to perform the parsing. datetime.datetime.strptime allows you to convert a datetime string to a datetime object. datetime.datetime.strftime allows you to convert a datetime object to the desired string.

dt_from, dt_to = [datetime.datetime.strptime(x, "%Y-%m-%d") for x in dt_list]
dt_str = f"From : {datetime.datetime.strftime('%b %d,%Y', dt_from)} | To: {datetime.datetime.strftime('%b %d,%Y', dt_to)}"]
DeGo
  • 783
  • 6
  • 14