Generate time series quarterly, one quarter growth

I looked through the arrow and python docs, it doesn't seem like it is step by step. For example, the following code gradually gives you a month, given the starting month so far. Looking at the arrow documents, the end of the month is convenient. what is there quarterly?

 import arrow from datetime import datetime a=arrow.Arrow.span_range('month', datetime(2012,7,1,0,0),datetime.now() ) for i in a: print i[1].floor('day').datetime.strftime("%Y-%m-%d") 

I am looking for a solution that runs a quarter to date

input: 14Q3

output:

 14Q3 14Q4 15Q1 15Q2 15Q3 
+5
source share
2 answers

To get the current quarter, use: (month - 1) // 3 + 1 . To create quarters in a given range:

 from datetime import date def generate_quarters(start, end): while start < end: #NOTE: not including *end* yield start start = start.increment() start = Quarter.from_string('14Q3') end = Quarter.from_date(date.today()) print("\n".join(map(str, generate_quarters(start, end)))) 

where Quarter is a simple subclass of namedtuple :

 from collections import namedtuple class Quarter(namedtuple('Quarter', 'year quarter')): __slots__ = () @classmethod def from_string(cls, text): """Convert 'NQM' into Quarter(year=2000+N, quarter=M).""" year, quarter = map(int, text.split('Q')) return cls(year + 2000, quarter) @classmethod def from_date(cls, date): """Create Quarter from datetime.date instance.""" return cls(date.year, (date.month - 1) // 3 + 1) def increment(self): """Return the next quarter.""" if self.quarter < 4: return self.__class__(self.year, self.quarter + 1) else: assert self.quarter == 4 return self.__class__(self.year + 1, 1) def __str__(self): """Convert to "NQM" text representation.""" return "{year}Q{quarter}".format(year=self.year-2000, quarter=self.quarter) 

Output

 14Q3 14Q4 15Q1 15Q2 15Q3 

The current quarter ( 15Q4 ) is not included.

+2
source

not really, but it works

 import arrow from datetime import datetime a=arrow.Arrow.span_range('month', datetime(2012,7,1,0,0),datetime.now() ) for i in a: print i[1].floor('day').datetime.strftime("%Y-%m-%d") b=[(x[1].date().month-1)//3 for x in a] c=[] for i in range(0,len(b),3): c.append(str(a[i][1].year)[2:]+"Q"+str(b[i])) 
0
source

Source: https://habr.com/ru/post/1233825/


All Articles