我查看了arrow
和python文档,似乎没有逐步增加的任何内容。例如,以下代码以递增的方式为您提供月份,给定起始月份。通过arrow
文档查看,月末很方便。有什么季度的吗?
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")
我正在寻找到目前为止逐个季度的解决方案
输入:14Q3
输出:
14Q3
14Q4
15Q1
15Q2
15Q3
答案 0 :(得分:2)
要获取当前季度,请使用:(month - 1) // 3 + 1
。要生成给定范围内的季度:
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))))
其中Quarter
是一个简单的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)
14Q3
14Q4
15Q1
15Q2
15Q3
不包括当前季度(15Q4
)。
答案 1 :(得分:0)
不漂亮,但有效
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]))