Home > Mobile >  How to convert all date objects from a list into datetime objects
How to convert all date objects from a list into datetime objects

Time:12-29

I have this list:

myList = [datetime.date(2021, 1, 1), datetime.date(2021, 2, 1), datetime.date(2021, 3, 1)]

I want to use a loop to replace all the date objects in this list with datetime objects. Any solutions?

CodePudding user response:

Just use datetime constructor:

import datetime

l1 = [datetime.date(2021, 1, 1), datetime.date(2021, 2, 1), datetime.date(2021, 3, 1)]
l2 = [
    datetime.datetime(year=d.year, month=d.month, day=d.day)
    for d in l1
]

print(l2)

CodePudding user response:

datetime.datetime.combine can be used to create a datetime.datetime from a datetime.date and a datetime.time. Pass datetime.time.min to get the start of the day

import datetime
myList = [datetime.date(2021, 1, 1), datetime.date(2021, 2, 1), datetime.date(2021, 3, 1)]

result = [datetime.datetime.combine(d, datetime.time.min) for d in myList]

CodePudding user response:

for date in myList:
    date = datetime.datetime(date.year, date.month, date.day)

if you want to use a for

CodePudding user response:

You can use help(datetime.date) and help(datetime.datetime) to find that date has attributes for year, month and day, and that datetime.datetime takes those values when its created. So make a list comprehension that does that

>>> import datetime
>>> myList = [datetime.date(2021, 1, 1), datetime.date(2021, 2, 1), datetime.date(2021, 3, 1)]
>>> newList = [datetime.datetime(d.year, d.month, d.day) for d in myList]
>>> newList
[datetime.datetime(2021, 1, 1, 0, 0), datetime.datetime(2021, 2, 1, 0, 0), datetime.datetime(2021, 3, 1, 0, 0)]
  • Related