如何正确设置日期时间格式?

2024-06-16 08:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法正确转换日期列

dte

                  date  Odds_Home  Odds_Draw  Odds_Away        Home_Team         Away_Team
0        Today, 12 Mar       3.82       3.35       2.10       Newcastle        Aston Villa
1     Tomorrow, 13 Mar       4.64       3.97       1.76           Leeds            Chelsea
2     Tomorrow, 13 Mar       1.90       3.49       4.54         Everton            Burnley
3     Tomorrow, 13 Mar       9.72       5.04       1.36          Fulham    Manchester City
4  2021-03-14 00:00:00       2.60       3.36       2.83         Arsenal          Tottenham
5  2021-03-14 00:00:00       1.87       3.60       4.48  Manchester Utd           West 

:

    dte['date'] = dte['date'].str.replace('Today', '2021')
    dte['date'] = dte['date'].str.replace('Tomorrow', '2021')
    dte['date'] = pd.to_datetime(dte['date'])
    print(dte)

如何在没有NaT的情况下将日期列正确转换为日期时间

        date  Odds_Home  Odds_Draw  Odds_Away        Home_Team         Away_Team
0 2021-03-12       3.82       3.35       2.10       Newcastle        Aston Villa
1 2021-03-13       4.64       3.97       1.76           Leeds            Chelsea
2 2021-03-13       1.90       3.49       4.54         Everton            Burnley
3 2021-03-13       9.72       5.04       1.36          Fulham    Manchester City
4        NaT       2.60       3.36       2.83         Arsenal          Tottenham
5        NaT       1.87       3.60       4.48  Manchester Utd           West Ham

dte['date'] = pd.to_datetime(dte['date'])

我犯了一个错误

raise ParserError("Unknown string format: %s", timestr)
dateutil.parser._parser.ParserError: Unknown string format: Today, 12 Mar

Tags: hometodaydatenatteammartomorrowdraw
1条回答
网友
1楼 · 发布于 2024-06-16 08:33:15

试试这个:

pd.to_datetime(df.date.str.replace('(Today|Tomorrow),', '2021'))

输出

0   2021-03-12
1   2021-03-13
2   2021-03-13
3   2021-03-13
4   2021-03-14
5   2021-03-14

相关问题 更多 >