pythonpandas

Exclude leap year days from date_range in pandas


I generate a series of dates like this:

pd.date_range("2001-01-01", "2012-12-31")

How can I automatically exclude the leap year dates? Feb 29th in the years where they occur?


Solution

  • From version 0.19.0 you can use DatetimeIndex.is_leap_year:

    rng = pd.date_range("2001-01-01", "2012-12-31")
    print (rng)
    DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04',
                   '2001-01-05', '2001-01-06', '2001-01-07', '2001-01-08',
                   '2001-01-09', '2001-01-10',
                   ...
                   '2012-12-22', '2012-12-23', '2012-12-24', '2012-12-25',
                   '2012-12-26', '2012-12-27', '2012-12-28', '2012-12-29',
                   '2012-12-30', '2012-12-31'],
                  dtype='datetime64[ns]', length=4383, freq='D')
    
    print (rng.is_leap_year)
    [False False False ...,  True  True  True]
    
    print (rng[~rng.is_leap_year])
    DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04',
                   '2001-01-05', '2001-01-06', '2001-01-07', '2001-01-08',
                   '2001-01-09', '2001-01-10',
                   ...
                   '2011-12-22', '2011-12-23', '2011-12-24', '2011-12-25',
                   '2011-12-26', '2011-12-27', '2011-12-28', '2011-12-29',
                   '2011-12-30', '2011-12-31'],
                  dtype='datetime64[ns]', length=3285, freq=None)