英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论