Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas date_range from DatetimeIndex to Date format

Tags:

python

pandas

Pandas date_range returns a pandas.DatetimeIndex which has the indexes formatted as a timestamps (date plus time). For example:

In  [114] rng=pandas.date_range('1/1/2013','1/31/2013',freq='D')
In  [115] rng
Out [116]
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00, ..., 2013-01-31 00:00:00]
Length: 31, Freq: D, Timezone: None

Given I am not using timestamps in my application, I would like to convert this index to a date such that:

In  [117] rng[0]
Out [118]
<Timestamp: 2013-01-02 00:00:00>

Will be in the form 2013-01-02.

I am using pandas version 0.9.1

like image 442
Jason Strimpel Avatar asked Jul 10 '13 17:07

Jason Strimpel


2 Answers

to_pydatetime returns a NumPy array of Python datetime.datetime objects:

In [8]: dates = rng.to_pydatetime()

In [9]: print(dates[0])
2013-01-01 00:00:00

In [10]: print(dates[0].strftime('%Y-%m-%d'))
2013-01-01
like image 163
unutbu Avatar answered Nov 11 '22 16:11

unutbu


For me the current answer is not satisfactory because internally it is still stored as a timestamp with hours, minutes, seconds.

Pandas version : 0.22.0

My solution has been to convert it to datetime.date:

In[30]: import pandas as pd
In[31]: rng = pd.date_range('1/1/2013','1/31/2013', freq='D')
In[32]: date_rng = rng.date   # Here it becomes date
In[33]: date_rng[0]
Out[33]: datetime.date(2013, 1, 1)
In[34]: print(date_rng[0])
2013-01-01
like image 35
mmngreco Avatar answered Nov 11 '22 16:11

mmngreco