Pandas date_range 从 DatetimeIndex 到 Date 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17576615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:59:17  来源:igfitidea点击:

Pandas date_range from DatetimeIndex to Date format

pythonpandas

提问by Jason Strimpel

Pandas date_rangereturns a pandas.DatetimeIndexwhich has the indexes formatted as a timestamps (date plus time). For example:

Pandasdate_range返回一个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

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.

将在表格中2013-01-02

I am using pandas version 0.9.1

我正在使用Pandas版本 0.9.1

采纳答案by unutbu

to_pydatetimereturns a NumPy array of Python datetime.datetimeobjects:

to_pydatetime返回 Pythondatetime.datetime对象的 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

回答by mmngreco

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

Pandas版本:0.22.0

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

我的解决方案是将其转换为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