Saturday 15 May 2010

python - Generate date ranges broken by month for a given period -


I am struggling to write a python, clean generator method, whose date range, such as ['2014 -01-15 ',' 2015-02-03] will give me:

  ['2014-01-15', '2014-01-31'] ['2014-02-01', '2014-02-28'] ... ['2015-02-01', '2015-02-03']  

This is What I came up with: datetime import datetime import calendar def genDatePeriods (startDate, endDate, format = '% Y-% m-% d') from:

 : dt1 = datetime.strptime (startDate) ), Format) dt2 = datetime.strptime (endDate, format) for the year in category (dt1.year, dt2.year + 1): range for the month (1, 13): d Ay0 = dt1.day if month == dt1 months and years == dt 1. this and 1 day 1 = dt 2. day if month == dt 2. mm and year == dt 2. this other calendar. Mothrange (year , Month) [1] If (year == DT 1.yure and month lieutenant; dt1.month) or (year == dt2.year and month> dt2.month): go ahead: D0 = (year, Month, day 0) D1 = (year, month, day 1) [d0, d1]]  

for d [datetime (* d) .strftime (format) Works, though I think that another dragon / clean / Usl way. datetime.date ()

The following is a very brief, code> objects To search each time on the first day of the next month, you do not reach the end date: datetime import from datetime, TimeDelta Def Jenadet Periods (StartDate, Endadet, Format = ' % Y -% m-% d '): curr = datetime.strptime (startdate, format) .date () end = datetime.strptime (endDate, format) .date () while curr & lt; = End: # the first day of the next day, modular arithmetic next_moth = curr.replace (month = curr.month% 12 + 1, year = curr.year + curr.month // 12, day = 1) curr_formatted = curr Strftime (format) # end date is the first day of the next month, zero to one day, # or the expiration date, whichever should be earlier, the first capacitance = formatted = minutes (next_ month - timeliness (day = 1), end ). Strawberry (format) yield [curr_formatted, end_formatted] curr = next_month

demo:

  & gt; & Gt; & Gt; For ridge in Junket Period ('2014-01-15', '2015-02-03'): ... print race ... ['2014-01-15', '2014-01-31'] [ '2014 -02-01', '2014-02-28'] ['2014-03-01', '2014-03-31'] ['2014-04-01', '2014-04-30'] ['2014-05-01,' 2014-05-31 '] [' 2014-06-01 ',' 2014-06-30 '] [' 2014-07-01 ',' 2014-07-31 '] ['2014-08-01', '2014-08-31'] ['2014-09-01', '2014-09-30'] ['2014-10-01', '2014-10-31' ] ['2014-11-01', '2014-11-30'] ['2014-12-01', '2014-12-31'] ['2015-01-01', '2015-01-31 '] [' 2015-02-01 ',' 2015-02-03 ']  

No comments:

Post a Comment