Use the code below to
I'd like to change from a text string to a date type, but
It will be in a different format.
How do I format the same date?
What you want to achieve
Save the text string to Excel and
I'd like to change from string to date type.
Text
country, date
US, 22/6/21
,2022/7/1
,2022/8/6
,22/4/29
Canada, 2022/7/5
Results you want to achieve
country, date
US, 2022/6/2022
,2022/7/1
,2022/8/6
,2022/4/29
Canada, 2022/7/5
country object
Date datetime64[ns]
dtype:object
Current actions
country, date
US, 2021-06-2200:00:00:00
,2022-07-01 00:00:00
,2022-08-06 00:00:00
,2029-04-22 00:00:00
Canada, 2022-07-05 00:00:00
country object
Date datetime64[ns]
dtype:object
How can I change it to a date type?
Professor, please.
Code
import pandas as pd
from datetime import datetime as dt, date, timedelta
input_folder=r "C:\Users\user\Documents\excel\test.txt"
output_folder=r "C:\Users\user\Documents\excel\test1.xlsx"
df=pd.read_table(input_folder, encoding='utf_8', sep=',')
# print(df.dtypes)
# String in specified format
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%Y/%#m/%#d").fillna('')
print(df.dtypes)
# Date type in specified format
df['Date'] = pd.to_datetime(df["Date", format="%Y / %m / %d")
print(df.dtypes)
df.to_excel(output_folder, encoding='utf_8_sig', index=False)
You should format the date_format
and datetime_format
arguments in pd.ExcelWriter
.
with pd.ExcelWriter("test2.xlsx", date_format="YYYY/MM/DD", datetime_format="YYY/MM/DD")aswriter:
df.to_excel(writer)
© 2025 OneMinuteCode. All rights reserved.