如何使用 Python Pandas 创建“yyyymmdd”格式的日期字符串列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/18684076/
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
How to create a list of date string in 'yyyymmdd' format with Python Pandas?
提问by bigbug
I want a list of date range in which each element is 'yyyymmdd'format string, such as : ['20130226','20130227','20130228','20130301','20130302'].
我想要一个日期范围列表,其中每个元素都是'yyyymmdd'格式字符串,例如 : ['20130226','20130227','20130228','20130301','20130302']。
I can use pandas to do so:
我可以使用Pandas来做到这一点:
>>> pandas.date_range('20130226','20130302')
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-02-26 00:00:00, ..., 2013-03-02 00:00:00]
Length: 5, Freq: D, Timezone: None
But it is DatetimeIndex and I need to do some extra format transform, so how to do that in a neat way ?
但它是 DatetimeIndex,我需要做一些额外的格式转换,那么如何以一种简洁的方式做到这一点?
回答by zero323
Or using list comprehension:
或者使用列表理解:
[d.strftime('%Y%m%d') for d in pandas.date_range('20130226','20130302')]
回答by falsetru
Using format:
使用format:
>>> r = pandas.date_range('20130226','20130302')
>>> r.format(formatter=lambda x: x.strftime('%Y%m%d'))
['20130226', '20130227', '20130228', '20130301', '20130302']
or using map:
或使用map:
>>> r.map(lambda x: x.strftime('%Y%m%d'))
array(['20130226', '20130227', '20130228', '20130301', '20130302'], dtype=object)
回答by Abhijit
For Just a daterange, pandaswould be an overkill when you actually again have to reformat the date using datetime. The following solution simply uses datetimeto serve your purpose
对于 Just a 来说daterange,pandas当您实际上再次必须使用datetime. 以下解决方案仅用于datetime满足您的目的
import datetime
def date_range(start_dt, end_dt = None):
    start_dt = datetime.datetime.strptime(start_dt, "%Y%m%d")
    if end_dt: end_dt = datetime.datetime.strptime(end_dt, "%Y%m%d")
    while start_dt <= end_dt:
        yield start_dt.strftime("%Y%m%d")
        start_dt += datetime.timedelta(days=1)
[e for e in date_range('20130226','20130302')]
['20130226', '20130227', '20130228', '20130301', '20130302']
回答by Maviles
Easy and clean: do it directly with pandas date_range and strftime like this:
简单而干净:直接使用 pandas date_range 和 strftime 这样做:
pd.date_range(start='20130226',end='20130302',freq='D').strftime('%Y%m%d')
Resulting:
结果:
Index(['20130226', '20130227', '20130228', '20130301', '20130302'], dtype='object')

