Skip to content Skip to sidebar Skip to footer

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

I have following dataframe. id int_date 1 20160228 2 20161231 3 20160618 4 20170123 5 20151124 How to convert above date in int format to date format of mm/dd/yyy

Solution 1:

You can use datetime methods.

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

Good Luck;

Solution 2:

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

Solution 3:

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]

Post a Comment for "Convert Integer (yyyymmdd) To Date Format (mm/dd/yyyy) In Python"