简体   繁体   English

将日期列(字符串)转换为日期时间并匹配格式

[英]Convert date column (string) to datetime and match the format

I'm trying to covert the next date column (str) to datetime64 and say that format doesn't match, can anyone help me pleas:)我试图将下一个日期列 (str) 隐藏到 datetime64 并说格式不匹配,任何人都可以帮助我请求:)

Column:柱子:

df["Date"] df[“日期”]

0 15/7/21... 2541 13/9/21 dtype: object 0 15/7/21... 2541 13/9/21 dtype: object

What I try:我尝试的是:

pd.to_datetime(df["Date"], format = "%d/%m/%Y") pd.to_datetime(df["日期"], 格式 = "%d/%m/%Y")

ValueError: time data '15/7/21' does not match format '%d/%m/%Y' (match) ValueError:时间数据“15/7/21”与格式“%d/%m/%Y”不匹配(匹配)

I also try:我也尝试:

pd.to_datetime(df["Date"].astype("datetime64"), format='%d/%m/%Y') pd.to_datetime(df["Date"].astype("datetime64"), format='%d/%m/%Y')

And it convert it as datetime but there is some date the day is in the month.并将其转换为日期时间,但该月有某个日期。

Anyone know what to do?有人知道该怎么办吗?

%Y expects a 4-digit year. %Y需要一个 4 位数的年份。 Use %y for a 2-digit year (See the docs ):使用%y作为两位数的年份(参见文档):

>>> import pandas as pd
>>> df = pd.DataFrame({'Date':['15/7/21','13/9/21']})
>>> df['Date']
0    15/7/21
1    13/9/21
Name: Date, dtype: object
>>> pd.to_datetime(df['Date'].astype('datetime64'),format='%d/%m/%y')
0   2021-07-15
1   2021-09-13
Name: Date, dtype: datetime64[ns]

Note that pandas is pretty good at guessing the format:请注意, pandas非常擅长猜测格式:

>>> pd.to_datetime(df['Date'])
0   2021-07-15
1   2021-09-13

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM