Reputation: 4842
I have a df which looks like:
df
date
[2021-08-31 00:00:00]
[2021-07-02 00:00:00, 2021-07-02 00:00:00]
[2021-08-31 00:00:00, 2021-09-15 00:00:00]
When I export it to .csv
I get a column looking like :
date
[Timestamp('2021-08-31 00:00:00')]
[Timestamp('2021-07-02 00:00:00'), Timestamp('2021-07-02 00:00:00')]
[Timestamp('2021-08-31 00:00:00'), Timestamp('2021-09-15 00:00:00')]
I want the .csv
file to have the same look as in df
without the Timestamp
and preferably without the hours, minutes, and seconds.
What I tried:
Checked if I can convert it like so:
for nr, item in enumerate(df['date']):
print(pd.to_datetime(item[nr],format='%Y%m%d'))
print(type(item[nr]))
break
But it still returns seconds which I don't understand why if I added the format
parameter.
2021-08-31 00:00:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
I tried:
def to_date(df):
res = []
for nr, item in enumerate(df['date']):
res.append(item[nr].date())
return res
df['test'] = to_date(df)
But I get:
IndexError: list index out of range
And I am not sure how I should convert it so that in my .csv
file I would get dates that would look like this 2021-08-31
.
Upvotes: 0
Views: 556
Reputation: 24304
try via map()
and list comprehension:
df['date']=df['date'].map(lambda x:[str(y) for y in x])
#you can also use apply() or agg() but they are slower then map()
Finally use to_csv()
method:
df.to_csv('filename.csv')
Update:
If you want only date part then:
df['date']=df['date'].map(lambda x:[str(y.date()) for y in x])
#as suggested by @MrFuppes
Upvotes: 1