'Python - Code returns dates but when added to list the format changes
I am trying to create a list of dates to add to a Pandas dataframe as a new column using ...
df['Surveys_Last_Week'] = list
I have done this before without issues. However, with the code below I get the dates returned in the format I want but when I add them to a list the format changes and they become prefixed with datetime.date
2022-05-14
2022-07-09
2022-03-05
2022-03-12
[datetime.date(2022, 5, 14), datetime.date(2022, 7, 9), datetime.date(2022, 3, 5), datetime.date(2022, 3, 12)]
How can I get the dates into a list in the format that they return in?
The code I am using is as follows ...
today = datetime.date.today()
completion_list_80 = []
for value in df.Weeks_to_80pc:
if value == float('inf'):
pass
else:
remaining_weeks = datetime.timedelta(weeks=value)
projected_completion = today + remaining_weeks
print(projected_completion)
completion_list_80.append(projected_completion)
print(completion_list_80)
Any help very much appreciated.
Thank you
Solution 1:[1]
To convert the list of datetime.date objects to a pandas.DatetimeIndex column using NumPy's datetime64 dtype, you can wrap pandas.to_datetime() around your list when you insert it into your DataFrame:
df['Surveys_Last_Week'] = pd.to_datetime(completion_list_80)
Alternatively, to convert the datetime.date objects to their yyy-mm-dd string representations, you can format them with strftime as you append them to the list (however, I would recommend sticking to pandas' builtin DatetimeIndex support):
completion_list_80.append(projected_completion.strftime('%Y-%m-%d'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Leimbigler |
