按季度生成时间序列,按四分之一递增 [英] generate time series by quarter, increment by one quarter

查看:136
本文介绍了按季度生成时间序列,按四分之一递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了箭头和python文档,似乎并没有按季度逐步增加的内容。例如,以下代码以递增的方式为您提供月份,直到现在为止为起始月份。通过箭头文档查看,月底很方便。

I looked through the arrow and python docs, doesn't seem to be anything that incrementally steps by quarter. For example, the following code incrementally gives you the month, given a starting month up until now. Looking thru the arrow docs, month end is convenient. anything out there that does 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 '正在寻找一个可以按季度更新的解决方案

I'm looking for a solution that steps by quarter up to now

输入: 14Q3

输出:

14Q3
14Q4
15Q1
15Q2
15Q3


推荐答案

获取当前季度,请使用: (month-1)// 3 +1 。生成给定范围内的季度:

To get the current quarter, use: (month - 1) // 3 + 1. To generate quarters in the 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))))

其中 Quarter 是一个简单的 dtuple 子类:

where Quarter is a simple namedtuple subclass:

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

当前季度( 15Q4 )不包括在内。

The current quarter (15Q4) is not included.

这篇关于按季度生成时间序列,按四分之一递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆