Generate List of Quarters Betweeen Given Dates

generate list of quarters betweeen given dates

Use date_range with add one quarter, last change format to strftime:

r = (pd.date_range(pd.to_datetime(start_date), 
pd.to_datetime(end_date) + pd.offsets.QuarterBegin(1), freq='Q')
.strftime('%B %Y')
.tolist())
print (r)
['March 2012', 'June 2012', 'September 2012', 'December 2012', 'March 2013', 'June 2013']

List of quarters between a particular day and today

If you're just trying to build the list you have here, you can iterate over the difference of the start year to the current year and then calculate the current quarter with parseInt(new Date().getMonth() / 3 + 1)

var d = new Date(),  y = d.getFullYear(),  m = d.getMonth(),  quarters = ['Jan-Feb-Mar', 'Apr-May-Jun', 'Jul-Aug-Sep', 'Oct-Nov-Dec'],  options = [];
for (var pastYear = 2016; pastYear < y; pastYear++) { quarters.forEach(q => options.push(q + ' ' + pastYear));}quarters.slice(0, parseInt(m / 3 + 1)).forEach(q => options.push(q + ' ' + y));
console.log("current date: " + d);console.log(options);

How to create a list of weeks/months/quarters between a range of two dates

To make your calculations work across multiple years, you should base them not on the endDate, but on the duration between the two dates. To do so, you can make your for loops going from the startDate to the startDate + duration.

I made an example for the calculation of the weeks : https://jsbin.com/xejocusana/edit?html,js,console

dateStart = "01-01-2018";
dateEnd = "03-31-2019";

start = moment(dateStart, "MM-DD-YYYY")
end = moment(dateEnd, "MM-DD-YYYY")

lowerRange = Math.floor(moment(dateStart, "MM-DD-YYYY").dayOfYear()/7);
// calculate the number of weeks between the two dates
numberOfWeeks = end.diff(start, 'weeks');
year = moment(dateStart, "MM-DD-YYYY").year();

weekListA = []
for (var i = lowerRange; i <= lowerRange + numberOfWeeks; i++) {
weekListA.push('W' + (i%52 +1) + '_' + (year+ Math.floor(i/52)));
}
console.log(weekListA);

I added :

  • a calculation of the numberOfWeeks, needed for the limit of the loop ;
  • a modulo + (i%52 +1) in the loop, to have the number of the week (You have to write +1 to make it begin at 0. Due to this constraint, you have to use Math.floor() instead of Math.ceil() when you calculate lowerRange) ;
  • a + Math.floor(i/52) in the loop, to increment the number of the year ;

I let you check if all the cases are covered (dates across more than 2 years, dates included or excluded, etc.)

get list of quarters between two dates (SQL)

You could try something like this, you would need to override the maximum recursion if you have a lot of quarters to list though:

DECLARE @start_date DATE = '20170101';
DECLARE @end_date DATE = '20170615';
WITH x AS (
SELECT
YEAR(@start_date) AS [year],
DATEPART(QUARTER, @start_date) AS [quarter]
UNION ALL
SELECT
CASE
WHEN [quarter] = 4 THEN [year] + 1
ELSE [year]
END AS [year],
CASE
WHEN [quarter] = 4 THEN 1
ELSE [quarter] + 1
END AS [quarter]
FROM
x
WHERE
[year] <= YEAR(@end_date)
AND [quarter] < DATEPART(QUARTER, @end_date))
SELECT * FROM x;

Find all quarters between 2 dates

This seems to work.

        public IEnumerable<DateTime> GetAllQuarters(DateTime current, DateTime past)
{
var curQ = (int)Math.Ceiling(current.Month / 3.0M);
var lastQEndDate = new DateTime(current.Year, curQ * 3, 1).AddMonths(-2).AddDays(-1);

do
{
yield return lastQEndDate;
lastQEndDate = lastQEndDate.AddMonths(-3);
} while (lastQEndDate > past);
}

python get the quarterly dates from a date range

With pure Python:

import datetime

start_date_str = "01/04/2020"
end_date_str = "01/04/2021"

start_date = datetime.datetime.strptime(start_date_str, "%d/%m/%Y").date()
end_date = datetime.datetime.strptime(end_date_str, "%d/%m/%Y").date()

print(f"Quarters within {start_date_str} and {end_date_str}:")
start_of_quarter = start_date
while True:
far_future = start_of_quarter + datetime.timedelta(days=93)
start_of_next_quarter = far_future.replace(day=1)
end_of_quarter = start_of_next_quarter - datetime.timedelta(days=1)
if end_of_quarter > end_date:
break
print(f"\t{start_of_quarter:%d/%m/%Y} - {end_of_quarter:%d/%m/%Y}")
start_of_quarter = start_of_next_quarter

How to get number of quarters between two dates in Java

while (cal1.getTime().after(cal.getTime()))

As soon as cal1.getTime() is "01-Apr-2015" it isnt "after" cal.getTime() anymore so the while loop will stop.
Thats why it doesnt make the last iteration which would give you the last Quarter.

you could go like:

while (cal1.getTime().after(cal.getTime()) || cal1.getTime().equals(cal.getTime()))

Generating sequence of dates quarterly

The from and to dates in the question are both end-of-quarter dates so we assume that that is the general case you are interested in.

1) Create a sequence of yearqtr objects yq and then convert them to Date class. frac=1 tells it s to use the end of the month. Alternately just use yq since that directly models years with quarters.

library(zoo)

from <- as.Date('1980-12-31')
to <- as.Date('1985-06-30')

yq <- seq(as.yearqtr(from), as.yearqtr(to), by = 1/4)
as.Date(yq, frac = 1)

giving;

 [1] "1980-12-31" "1981-03-31" "1981-06-30" "1981-09-30" "1981-12-31"
[6] "1982-03-31" "1982-06-30" "1982-09-30" "1982-12-31" "1983-03-31"
[11] "1983-06-30" "1983-09-30" "1983-12-31" "1984-03-31" "1984-06-30"
[16] "1984-09-30" "1984-12-31" "1985-03-31" "1985-06-30"

2) or without any packages add 1 to from and to so that they are at the beginning of the next month, create the sequence (it has no trouble with first of month sequences) and then subtract 1 from the generated sequence giving the same result as above.

seq(from + 1, to + 1, by = "quarter") - 1

Get all quarters in Month, Year format between two dates

You can use a recursive CTE to generate the dates as follows:

declare @StartDate datetime
declare @EndDate datetime
select @StartDate='2011-01-23' , @EndDate='2015-11-29'

;With Quarters as (
select DATEADD(quarter,DATEDIFF(quarter,0,@StartDate),0) as dt
union all
select DATEADD(quarter,1,dt)
from Quarters
where dt < DATEADD(quarter,DATEDIFF(quarter,0,@EndDate),0)
)
select
--I'd usually keep them as dates at this point, but to match your requirement
CONVERT(varchar(3),dt,109) + ' ' + CONVERT(varchar(4),dt,120)
from Quarters order by dt

This also uses a couple of other tricks - it uses CONVERT with far too short target datatypes to quickly truncate the strings to just the parts that we want to keep - and it uses a DATEADD/DATEDIFF pair to quickly round a datetime value down to it's nearest interval boundary.

For SQL Server 2012, you could instead use FORMAT to produce the output string, but I've not experimented with that much so I'll leave that as an exercise...

How can i get number of quarters between two dates in PostgreSQL?

MSSQL 0 is the date '1900-01-01' in DATEDIFF(QQ, 0, '2018-09-05'), that function will get the number of QUARTER from 1900-01-01 to 2018-09-05

But PostgreSQL does not have a QUARTER number function.

You can try to use

  1. EXTRACT(QUARTER FROM TIMESTAMP '2018-09-05') to get this month QUARTER number.

  2. date_part('year',age('2018-09-05','1900-01-01')) get year number between
    '2018-09-05' and '1900-01-01'.

then do some calculation.

select (EXTRACT(QUARTER FROM TIMESTAMP '2018-09-05') + 
date_part('year',age('2018-09-05','1900-01-01')) * 4) -1 QUARTER

Results:

| quarter |
|---------|
| 474 |


Related Topics



Leave a reply



Submit