Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python [duplicate]

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?

like image 650
Sushant Kulkarni Avatar asked Mar 31 '17 06:03

Sushant Kulkarni


People also ask

How do you change date format from Yyyymmdd to mm/dd/yyyy in Python?

Use strftime() function of a datetime class For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I convert a number to a date in Python?

You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp.


2 Answers

You can use datetime methods.

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

Good Luck;

like image 131
Mr Sam Avatar answered Oct 16 '22 14:10

Mr Sam


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
like image 7
aghast Avatar answered Oct 16 '22 16:10

aghast