13

Pandasdate_range返回 a pandas.DatetimeIndex,其索引格式为时间戳(日期加时间)。例如:

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

鉴于我没有在我的应用程序中使用时间戳,我想将此索引转换为这样的日期:

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

将在表格中2013-01-02

我正在使用熊猫版本 0.9.1

4

2 回答 2

12

to_pydatetimedatetime.datetime返回 Python对象的 NumPy 数组:

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
于 2013-07-10T17:04:04.613 回答
12

对我来说,当前的答案并不令人满意,因为在内部它仍然存储为带有小时、分钟、秒的时间戳。

熊猫版本:0.22.0

我的解决方案是将其转换为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
于 2019-02-20T09:02:00.897 回答