简体   繁体   中英

Generating dates with an interval of one year with month and day being constant in python

I have a few dates stored in a list U, I want to generate a sequence of dates for every individual date from years 1981 to 2018 with month and day being constant. I have used relativedelta() command from dateutil library.

    from dateutil.relativedelta import relativedelta
    import datetime
    
    U=[datetime.date(2013,6,5),datetime.date(2014,7,8),datetime.date(2012,12,5)]
    U[0]+relativedelta(years=1) 

But relativedelta(years=1) will fetch only datetime.date(2014,6,5) , how to generate dates as datetime.date(1981,Month,Day) , datetime.date(1982,Month,Day) so on till datetime.date(2018,Month,Day) for all the three different dates in U

You can keep it simple by using a list comprehension. If lets say, you want all First of Januaries between 1980 & 2019:

[datetime.datetime(year, 1, 1) for year in range(1980,2020)]

(If want October 30, change 1 , 1 to 10 , 30 , for example.

Thank you Zabop for the solution. I wanted to generate the sequence for all the three dates, here is the code:

import numpy as np
import datetime

U=[datetime.date(2013,6,5),datetime.date(2014,7,8),datetime.date(2012,12,5)]
x=list()
for i in np.arange(0,3,1):
           X1=[datetime.datetime(year, U[i].month, U[i].day) for year in range(1980,2020)]
           x.append(X1) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM