将列转换为特定的日期格式,其中包含Python中不同格式的日期

发布于 2025-01-14 13:00:38 字数 570 浏览 0 评论 0原文

这是我的数据框:

 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

我想要“日期”列中的所有日期采用 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

此处格式 21.03.12 未被识别为 yy.mm.dd 。请纠正 我在 yy.mm.dd 格式日期前面添加了“20”,这有效但无效 一个永久的解决方案。有没有更好的解决办法?

This is my data frame:

 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

I want all the dates from 'Date' column in yyyy-mm-dd format. The expected output is given below

     Date
0   2015-01-05
1   2009-07-15
2   2021-03-12
3   2021-03-12

But i am getting

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天旳寂寞 2025-01-21 13:00:38

我认为您正在追求以下结果:

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 现在如何解释为年份。

I think you're after this:

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)

Result:

          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

In 'Desired', note how 21 is now interpreted as the year.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文