Excel store date Column call Today and data type is date
Today |
---|
13/12/2021 |
14/12/2021 |
15/12/2021 |
when i import the excel to another excel using python, how to change the date type to text type?
below is my code and try to convert, but not work. could anyone give me advise? thanks
data.insert(0, {'Date':datetime.strptime(str(Today),'%d/%m/%Y').strftime('%d/%m/%Y')})
Excel try to recognize date format even if you cast your column Today
as string.
Suppose the following dataframe:
df = pd.DataFrame({'ID': [123, 456, 789], 'Name': ['Louis', 'Paul', 'Alexandre'],
'Today': pd.date_range('2021-12-14', periods=3, freq='D')})
print(df)
# Output:
ID Name Today
0 123 Louis 2021-12-14
1 456 Paul 2021-12-15
2 789 Alexandre 2021-12-16
If you export your dataframe with df.to_excel('data.xlsx', index=False)
, you got:
Here, the trick:
with pd.ExcelWriter('data.xlsx') as writer:
df.to_excel(writer, index=False)
wb = writer.book
ws = wb.active
# For the third column only (Today, Col C)
for col in ws.iter_cols(min_col=3, max_col=3):
# For all rows below header (C2, C3, C4, ...)
for cell in col[1:]:
cell.number_format = 'DD/MM/YYYY'
Now, you got:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.