17

I want a list of date range in which each element is 'yyyymmdd' format string, such as : ['20130226','20130227','20130228','20130301','20130302'] .

I can use pandas to do so:

>>> 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 ?

4 Answers 4

38

Or using list comprehension:

[d.strftime('%Y%m%d') for d in pandas.date_range('20130226','20130302')]
Sign up to request clarification or add additional context in comments.

Comments

21

Using 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:

>>> r.map(lambda x: x.strftime('%Y%m%d'))
array(['20130226', '20130227', '20130228', '20130301', '20130302'], dtype=object)

1 Comment

Thanks for the tip of using .format(formatter=lambda x: x.strftime('%Y%m%d'))
11

Easy and clean: do it directly with pandas date_range and strftime like this:

pd.date_range(start='20130226',end='20130302',freq='D').strftime('%Y%m%d')

Resulting:

Index(['20130226', '20130227', '20130228', '20130301', '20130302'], dtype='object')

Comments

4

For Just a daterange, pandas would be an overkill when you actually again have to reformat the date using datetime. The following solution simply uses datetime to serve your purpose

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']

2 Comments

Helpful function. Thanks.
I love this solution. pandas should not be used just for this problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.