I have been working on a function that will take three strings in a list, one for the year, one for the month, and one for the day, and have it return a date that represents that day.
from datetime import datetime
def make_a_date(values):
date1 = ""
for value in values:
date1 = value
date2 = datetime.datetime(int(date1)).date()
return date2
print(make_a_date(["2022", "11", "8"]))
The above code however gives the error:
Traceback (most recent call last):
File "<string>", line 9, in <module>
File "<string>", line 6, in make_a_date
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'`
CodePudding user response:
you can fix your import a bit and use more builtin python functions to achieve this result
from datetime import date
def make_a_date(values):
date2 = date(*map(int,values))
return date2
print(make_a_date(["2022", "11", "8"]))
or one liner if you don't want a function
from datetime import date
print(date(*map(int, ["2022", "11", "8"])))
CodePudding user response:
def make_a_date(values):
date2 = datetime(year = values[0], month = values[1], day = values[2])
return date2
print(make_a_date([2022, 11, 8]))
CodePudding user response:
You can use datetime.strptime
def make_a_date(values):
date1 = "-".join(values)
# print(date1)
date2 = datetime.strptime(date1, "%Y-%m-%d").date()
return date2
print(make_a_date(["2022", "11", "8"]))
Output:
2022-11-08