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 ?
CodePudding user response:
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)}"]
CodePudding user response:
You only get one value back from your to_date
function because you exit the function in the first iteration of the loop. 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.