当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Working on dates with mm-dd-YY & YY-mm-dd format in pandas

问题描述:

I am trying to do a simple test on pandas capabilities to handle dates & format.

For that i have created a dataframe with values like below. :

df = pd.DataFrame({'date1' : ['10-11-11','12-11-12','10-10-10','12-11-11',

'12-12-12','11-12-11','11-11-11']})

Here I am assuming that the values are dates. And I am converting it into proper format using pandas' to_datetime function.

df['format_date1'] = pd.to_datetime(df['date1'])

print(df)

Out[3]:

date1 format_date1

0 10-11-11 2011-10-11

1 12-11-12 2012-12-11

2 10-10-10 2010-10-10

3 12-11-11 2011-12-11

4 12-12-12 2012-12-12

5 11-12-11 2011-11-12

6 11-11-11 2011-11-11

Here, Pandas is reading the date of the dataframe as "MM/DD/YY" and converting it in native format (i.e. YYYY/MM/DD). I want to check if Pandas can take my input indicating that the date format is actually "YY/MM/DD" and then let it convert into its native format. This will change the value of row no.: 5. To do this, I have run following code. But it is giving me an error.

df3['format_date2'] = pd.to_datetime(df3['date1'], format='%Y/%m/%d')

ValueError: time data '10-10-10' does not match format '%Y/%m/%d' (match)

I have seen the sort of solution here. But I was hoping to get a little easy and crisp answer.

网友答案:

%Y in the format specifier takes the 4-digit year (i.e. 2016). %y takes the 2-digit year (i.e. 16, meaning 2016). Change the %Y to %y and it should work.

Also the dashes in your format specifier are not present. You need to change your format to %y-%m-%d

分享给朋友:
您可能感兴趣的文章:
随机阅读: