29

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/yyyy? Want this in particular format for further excel operations?

id int_date  
1  02/28/2016  
2  12/31/2016  
3  06/18/2016
4  01/23/2017
5  11/24/2015

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

but date is in datetime object, how to put it as date in pandas DF?

fantabolous
  • 21,470
  • 7
  • 54
  • 51
Sushant Kulkarni
  • 439
  • 1
  • 4
  • 11
  • This question is wrt a column in a pandas dataframe, in which case it's inappropriate to apply the conversion item by item and is not a duplicate of the marked question. A better answer is https://stackoverflow.com/questions/27506367/python-pandas-integer-yyyymmdd-to-datetime – fantabolous Jun 03 '19 at 08:08

3 Answers3

65

You can use datetime methods.

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

Good Luck;

Mr Sam
  • 981
  • 1
  • 8
  • 12
7

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
aghast
  • 14,785
  • 3
  • 24
  • 56
4

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]
N. Walter
  • 99
  • 3
  • 2
    For that last line to work it should read something like: `datetime.date(int(date_string[0:4]), int(date_string[4:6]), int(date_string[6:8]))` – Mario Ruggier Jan 30 '19 at 14:58