Python:根据季度计算月份,季度详细信息

时间:2017-05-01 00:31:54

标签: python datetime python-datetime

我正在尝试按季度计算月份,季度详情

示例:当前日期= 2017年4月29日

I / p:

No_of_quarters=6

O / p:

Quarters = ["Q1-2016","Q2-2016", "Q3-2016", "Q4-2016", "Q1-2017", "Q2-2017"]
Months = ["Jan-2016","Feb-2016","Mar-2016","Apr-2016","May-2016","Jun-2016","Jul-2016","Aug-2016","Sep-2016","Oct-2016","Nov-2016","Dec-2016","Jan-2017","Feb-2017","Mar-2017","Apr-2017"]

我可以重复使用任何预定义的功能吗?或者我需要使用以下方式计算

today = datetime.date.today()
month = int(today.strftime("%m")) - 1 
quarter = month / 3 + 1
quarter_Name = "Q" + str(quarter)  + "-" +  today.strftime("%Y")
month_name = today.strftime("%b") + "-" +  today.strftime("%Y")

2 个答案:

答案 0 :(得分:2)

使用pandas和no_of_quarters输入

import pandas as pd
import datetime

No_of_quarters=6

today = datetime.date.today()
month = pd.Period(today, freq='M')
quarter = month.asfreq('Q-DEC')

print "Quarters:"
for x in range (0,No_of_quarters-1):
    print quarter-x

print "Months:"
for x in range (0,(No_of_quarters*3)-1):
    print month-x

答案 1 :(得分:1)

Try timeindex in pandas

示例:

import pandas as pd
prng = pd.period_range('01/01/2017', '04/29/2017', freq='Q')

print(prng)
PeriodIndex(['2017Q1', '2017Q2'], dtype='period[Q-DEC]', freq='Q-DEC')

# Change freq to 'M'
prng = pd.period_range('01/01/2017', '04/29/2017', freq='M')

print(prng)
PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04'],
             dtype='period[M]', freq='M')