将列转换为特定的日期格式,其中包含 python 中不同的日期格式
Convert a column to a specific date format which contains different formats of date in python
这是我的数据框
df = pd.DataFrame({
'Date': ['01/05/2015', '15 Jul 2009', '21.03.12','2021.03.12']
})
Date
0 01/05/2015
1 15 Jul 2009
2 21.03.12
3 2021.03.12
我希望 'Date' 列中的所有日期都采用 yyyy-mm-dd 格式。预期输出如下
Date
0 2015-01-05
1 2009-07-15
2 2021-03-12
3 2021-03-12
但我得到了
Date
0 2015-01-05
1 2009-07-15
2 2012-03-21
3 2021-03-12
Here, the format 21.03.12 is not recognized as yy.mm.dd .To rectify
this I added '20' infront of yy.mm.dd format dates, this works but not
a permanent solution. Is there any better solution for this?
Thanks in advance!
我想你在找这个:
import pandas as pd
df = pd.DataFrame({
'Date': ['01/05/2015', '15 Jul 2009', '21.03.12', '2021.03.12']
})
df['Current'] = pd.to_datetime(df['Date'])
df['Desired'] = pd.to_datetime(df['Date'], yearfirst=True)
print(df)
结果:
Date Current Desired
0 01/05/2015 2015-01-05 2015-01-05
1 15 Jul 2009 2009-07-15 2009-07-15
2 21.03.12 2012-03-21 2021-03-12
3 2021.03.12 2021-03-12 2021-03-12
在 'Desired'
中,请注意 21
现在如何解释为年份。
这是我的数据框
df = pd.DataFrame({
'Date': ['01/05/2015', '15 Jul 2009', '21.03.12','2021.03.12']
})
Date
0 01/05/2015
1 15 Jul 2009
2 21.03.12
3 2021.03.12
我希望 'Date' 列中的所有日期都采用 yyyy-mm-dd 格式。预期输出如下
Date
0 2015-01-05
1 2009-07-15
2 2021-03-12
3 2021-03-12
但我得到了
Date
0 2015-01-05
1 2009-07-15
2 2012-03-21
3 2021-03-12
Here, the format 21.03.12 is not recognized as yy.mm.dd .To rectify this I added '20' infront of yy.mm.dd format dates, this works but not a permanent solution. Is there any better solution for this?
Thanks in advance!
我想你在找这个:
import pandas as pd
df = pd.DataFrame({
'Date': ['01/05/2015', '15 Jul 2009', '21.03.12', '2021.03.12']
})
df['Current'] = pd.to_datetime(df['Date'])
df['Desired'] = pd.to_datetime(df['Date'], yearfirst=True)
print(df)
结果:
Date Current Desired
0 01/05/2015 2015-01-05 2015-01-05
1 15 Jul 2009 2009-07-15 2009-07-15
2 21.03.12 2012-03-21 2021-03-12
3 2021.03.12 2021-03-12 2021-03-12
在 'Desired'
中,请注意 21
现在如何解释为年份。