0

Excel store date column called 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 advice? Thanks

data.insert(0, {'Date':datetime.strptime(str(Today),'%d/%m/%Y').strftime('%d/%m/%Y')})
2
  • from datetime import datetime today = '13/12/2021' type(datetime.strptime(str(today),'%d/%m/%Y').strftime('%d/%m/%Y')) <class 'str'> Commented Dec 14, 2021 at 6:26
  • Hi @ShekharSamanta , thank you for your advise, but when i open the excel , the column is date type , can i convert the type to text before open excel?thanks Commented Dec 14, 2021 at 6:53

1 Answer 1

1

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:

enter image description here

Here, the trick:

with pd.ExcelWriter('data.xlsx', engine='openpyxl') 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:

enter image description here

Sign up to request clarification or add additional context in comments.

8 Comments

HI @Corralien , thank you for your support! I have used pip install to install openpyxl and use from openpyxl import Workbook but cannot use active and "workbook is not accessed" : show AttributeError: 'Workbook' object has no attribute 'active'
@iamnew. Does it work for you?
Hi @Corralien , could i ues this way to export excel and convert number format? thanks self.Today.to_excel(self.path+"Today.xlsx", sheet_name = 'Sheet3', index=False, engine='xlsxwriter')
The engine I used is openpyxl not xlsxwriter.
Hi Corralien, worbook active not work ,any advise to convert the date to text? thank so much
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.