pandas的date_time未将字符串转换为日期格式。

huangapple go评论71阅读模式
英文:

pandas date_time not converting the string into date format

问题

I have data of Jan-91 (mmm-YY) format. I am trying to convert is using pandas date_time function with code -
data['Month'] = pd.to_datetime(data['Month'], format = '%b-%y')
However getting the error as
time data 'Jan-91' does not match format '%b-%y' (match)

time data 'Jan-91' does not match format '%b-%y' (match)

I am trying to expecting the output should be DD-MM-YYYY format.

英文:

I have data of Jan-91 (mmm-YY) format. I am trying to convert is using pandas date_time function with code -
data['Month'] = pd.to_datetime(data['Month'], format = '%ddd-%YY')
However getting the error as
time data 'Jan-91' does not match format '%ddd-%YY' (match)

time data 'Jan-91' does not match format '%ddd-%YY' (match)

I am trying to expecting the output should be DD-MM_YYYY format.

答案1

得分: 1

你的日期时间格式有点问题。应该使用"%b-%y"而不是"%ddd-%YY",也就是代码片段应该是:

data['Month'] = pd.to_datetime(data['Month'], format='%b-%y')

如果你查看pandas.to_datetime的文档,在format部分,它说它使用strftime语法来获取日期格式。在strftime和strptime格式代码下,你会看到正确的格式代码是%b表示3个字母的月份缩写,%y表示没有世纪的零填充年份。

然后,为了将日期转换为你想要的格式,你需要第二行代码来重新赋值Month列:

data['Month'] = data['Month'].dt.strftime(date_format='%d-%m_%Y')
英文:

your datetime format is a little off. Instead of %ddd-%YY it should read "%b-%y". i.e. the code snippet should read:

data['Month'] = pd.to_datetime(data['Month'], format = '%b-%y')

If you look at the documentation for pandas.to_datetime, under format, it says that it uses strftime syntax to get the date format. Under strftime and strptime format codes, you will see the correct format codes are %b for a 3 letter month abbreviation, and %y for a zero-padded year without a century.

Then, to get the date into your desired format, you will need a second line to reassign the Month column:

data['Month'] = data['Month'].dt.strftime(date_format = '%d-%m_%Y')

答案2

得分: 0

根据 Pandas 文档format 参数仅用于解析,而不是用于目标格式。因此,要获取您期望的输出,您首先必须解析为默认格式,然后使用 `` 生成您期望的格式:

data['Month'] = pd.to_datetime(data['Month'])
data['Month'] = data['Month'].dt.strftime('%d-%m_%Y')
英文:

According the Pandas documents, the format argument is only for parsing not for the destination format. So to get your desired output, you have to first parse into the default format, and then use the `` to produce your expected format:

data['Month'] = pd.to_datetime(data['Month'])
data['Month'] = data['Month'].dt.strftime('%d-%m_%Y')

huangapple
  • 本文由 发表于 2023年5月21日 13:28:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定