python 2.7 - Converting to date format in pandas -
i have dataframe contains column holds:
date: 31062005 072005 12005 2012   i convert these dates format:
date: 31/06/2005 07/2005 01/2005 2012   what simplest way this? fields not in date format yet, strings.
suppose write function
def convert_date(s):     if len(s) == 4:         return s     elif len(s) < 7:         return s[: -4].zfill(2) + '/' + s[-4: ]     else:         return s[: -6].zfill(2) + '/' + s[-6: -4].zfill(2) + '/' + s[-4]   then if dates in df.dates, can use
>>> df.dates.apply(convert_date)                                    0    31/06/2 1    07/2005 2    01/2005 3       2012 name: dates, dtype: object   note converts string in 1 form string in different form, meaning can't manipulate dates further. if want that, i'd suggest amend preceding function use appropriate datetime.datetime.strptime format matching length of string. this:
def convert_date(s):     if len(s) == 4:         return datetime.datetime.strptime('%y')     elif len(s) < 8:         return datetime.datetime.strptime('%m%y')     else:         return datetime.datetime.strptime('%d%m%y')   note first date (with 31 days) seems illegal, though.
Comments
Post a Comment