0

Is there a way to generate a list of dates in the form YearMonthDay in Python? I need to make a list containing dates in that format for every Saturday between June 12 2010 and December 8 2012.

I tried pandas.date_range('6/12/2010','12/8/2012', freq='W-SAT') but I was unable to convert the resulting timestamp objects to the format mentioned above.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
user1799242
  • 495
  • 3
  • 9
  • 12

4 Answers4

2

Since pandas 0.8 the Timestamp type subclasses the standard datetime class in the standard library. Consequently, you can use datetime.strftime,

>>> [ d.strftime('%Y%m%d') for d in pandas.date_range('6/12/2010','12/8/2012', freq='W-SAT') ]
['20100612',
 '20100619',
 '20100626',
 '20100703',
...
bgamari
  • 5,913
  • 1
  • 18
  • 21
0

Yes, you take the datetime library and create the first of the saturday with that as a date object. Then you create a timedelta object of 7 days, and add that to the first date object. Keep adding until you reached the last Saturday.

To create a string in the 'yearmonthday' format from these objects it's easiest to use the .strftime() methods of the objects.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
0

Something like this should work to get the dates (using only datetime in the standard library).

from datetime import date,timedelta

def first_sat_after(d):
    for i in range(7):
        new_day = d.replace(day = d.day + i)
        if new_day.weekday() == 6:
            return new_day

def weekday_range(d1,dend):
    week = timedelta(days = 7)
    yield d1
    d2 = d1 + week
    while d2 <= dend:
        yield d2
        d2 = d2 + week

So then your program would look something like:

d1 = date(2010,6,12)
dend = date(2012,8,12)

date_strings = [ x.strftime('%Y%m%d') for x in weekday_range(first_sat_after(d1),dend) ]
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

I think you just want to use formatting (although not convinced this requires pandas! - look at dateutil or just utilising the builtin datetime module):

>>> dr = pandas.date_range('6/12/2010','12/8/2012', freq='W-SAT')
>>> ['{:%B %d %Y}'.format(d) for d in dr[:5]]
['June 12 2010', 'June 19 2010', 'June 26 2010', 'July 03 2010', 'July 10 2010']
>>> ['{:%Y%m%d}'.format(d) for d in dr[:5]]
['20100612', '20100619', '20100626', '20100703', '20100710']
Jon Clements
  • 138,671
  • 33
  • 247
  • 280