我有2列日期格式:2019年5月1日和19年5月1日。我想要1/5/2019格式的文件。
此处提到的代码似乎并未更改1列的格式,我需要将两列都转换为1/5/2019格式
df['billing_start_date'] = (pd.to_datetime(df['billing_start_date'], format='%Y/%m/%d').dt.strftime('%m/%d/%Y'))
答案 0 :(得分:0)
将to_datetime
与Series.dt.strftime
一起用于不同的format
:
df = pd.DataFrame({"a":["5/1/2019"], "b":["1-May-19"]})
df['a'] = pd.to_datetime(df['a'], format='%m/%d/%Y').dt.strftime('%m/%d/%Y')
df['b'] = pd.to_datetime(df['b'], format='%d-%b-%y').dt.strftime('%m/%d/%Y')
print (df)
a b
0 05/01/2019 05/01/2019
答案 1 :(得分:0)
# I guess you have two different columns with different dateformats as per the # question , please check the below answer.
from datetime import datetime
df=pd.DataFrame({'start_date':['5/1/2019','7/11/2019','3/10/2019'],
'end_date':['1-May-19','2-Mar-19','11-May-19']})
df
start_date end_date
0 5/1/2019 1-May-19
1 7/11/2019 2-Mar-19
2 3/10/2019 11-May-19
def try_parsing_date(text):
for fmt in ("%m/%d/%Y",'%d-%b-%y'):
try:
return datetime.strptime(text, fmt).strftime('%d/%m/%Y')
except ValueError:
pass
raise ValueError('no valid date format found')
df['new_start_date']=df['start_date'].apply(try_parsing_date)
df['new_end_date']=df['end_date'].apply(try_parsing_date)
df
start_date end_date new_start_date new_end_date
0 5/1/2019 1-May-19 01/05/2019 01/05/2019
1 7/11/2019 2-Mar-19 11/07/2019 02/03/2019
2 3/10/2019 11-May-19 10/03/2019 11/05/2019
答案 2 :(得分:0)
您采用正确的方法,但执行错误
我们的首发df:
df = pd.DataFrame({"col_1":["5/1/2019"], "col_2":["1-May-19"]})
col_1 col_2
5/1/2019 1-May-19
这是如何通过简单的解决方案实现这一目标:
df["col_1"] = pd.to_datetime(df["col_1"])
df["col_2"] = pd.to_datetime(df["col_1"])
df["col_1"] = df["col_1"].dt.strftime('%d/%m/%Y')
df["col_2"] = df["col_2"].dt.strftime('%d/%m/%Y')
给出:
col_1 col_2
01/05/2019 01/05/2019
或两行带有方法链接
df["col_1"] = pd.to_datetime(df["col_1"]).dt.strftime('%d/%m/%Y')
df["col_2"] = pd.to_datetime(df["col_1"]).dt.strftime('%d/%m/%Y')