Convert Integer (YYYYMMDD) To Date Format (mm/dd/yyyy) In Python


Answer :

You can use datetime methods.



from datetime import datetime
a = '20160228'
date = datetime.strptime(a, '%Y%m%d').strftime('%m/%d/%Y')


Good Luck;



Build a new column with applymap:



import pandas as pd

dates = [
20160228,
20161231,
20160618,
20170123,
20151124,
]

df = pd.DataFrame(data=list(enumerate(dates, start=1)), columns=['id','int_date'])

df[['str_date']] = df[['int_date']].applymap(str).applymap(lambda s: "{}/{}/{}".format(s[4:6],s[6:], s[0:4]))

print(df)


Emits:



$ python test.py
id int_date str_date
0 1 20160228 02/28/2016
1 2 20161231 12/31/2016
2 3 20160618 06/18/2016
3 4 20170123 01/23/2017
4 5 20151124 11/24/2015


There is bound to be a better solution to this, but since you have zeroes instead of single-digit elements in your date (i.e. 06 instead of 6), why not just convert it to string and convert the subsections?



using datetime would also get you the month strings etc.



//edit:
to be a little more precise, something like this should do the job:



def get_datetime(date):
date_string = str(date)
return datetime.date(date_string[:3], date_string[4:6], date_string[6:8]


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable