python - Applying datetime format in pandas for sorting -
in pandas, have column dates of format: %y/%m/%d (e.g. 2015/10/31). want change format like: %d-%m-%y (e.g. 31-10-15).
turning column correct object later sorting:
df['date'] = pd.to_datetime(df['date'])
applying strptime:
df['date'] = df['date'].apply(lambda x: datetime.strptime(x,'%d-%m-%y')) typeerror: must str, not timestamp
also, oddly, if dates enter pandas dataframe in other default iso standard weird results occur on sorting. such inconsistent formats and/or not sorting:
0 2015-01-31 1 2016-15-01
because dealing datetime object already, getting error because strptime
requires string , not timestamp
object. definition of strptime
:
def strptime(cls, date_string, format): 'string, format -> new datetime parsed string (like time.strptime()).'
what looking first convert datetime format require in string using strftime
:
def strftime(self, format): """return string representing date , time, controlled explicit format string.
and bring datetime
object using strptime
. following demo demonstrate. note use of .date()
@ end in order remove unneeded 00:00:00
time portion.
>>> datetime import datetime >>> orig_datetime_obj = datetime.strptime("2015/10/31", '%y/%m/%d').date() >>> print(orig_datetime_obj) 2015-10-31 >>> print(type(orig_datetime_obj)) <type 'datetime.datetime'> >>> new_datetime_obj = datetime.strptime(orig_datetime_obj.strftime('%d-%m-%y'), '%d-%m-%y').date() >>> print(new_datetime_obj) 2015-10-31 >>> print(type(new_datetime_obj)) <type 'datetime.date'>
alternatively, if require converting different format in string, can stick using strftime
new format. using example above, need portion:
orig_datetime_obj.strftime('%d-%m-%y')
Comments
Post a Comment