Stefano Fedele
Stefano Fedele

Reputation: 7423

How can I convert a series of integers into dates?

I have a pandas Series of integers such as

151215

I want to convert these integers in dates

2015-12-15

That means 15th December 2015. A quick search on pandas websites suggests me to use the to_datetime() method. Unfortunately I realised that if the the pandas data is a string

st = '151215'
pd.to_datetime(st)

then it works correctly (except the fact that I don't need the time)

Timestamp('2015-12-15 00:00:00')

but when pandas data are integers

st = 151215
pd.to_datetime(st)

the result is

Timestamp('1970-01-01 00:00:00.000151215')

Could you suggest me an efficient way to convert a list of integers into dates

Upvotes: 1

Views: 159

Answers (1)

Grr
Grr

Reputation: 16099

You can just use pandas.to_datetime no need to convert to string first (at least in pandas 0.19):

dates = pd.Series([151215]*8)
dates = pd.to_datetime(dates, format="%y%m%d")
print(dates)
0   2015-12-15
1   2015-12-15
2   2015-12-15
3   2015-12-15
4   2015-12-15
5   2015-12-15
6   2015-12-15
7   2015-12-15
dtype: datetime64[ns]

Converting a single value as in your example will result in Timestamp('2015-12-15 00:00:00'), but if you pass the entire series the result looks like the above.

Upvotes: 3

Related Questions