要求: 得到以下 -第一季度的第一天和最后一天 -第二季度的第一天和最后一天 -第三季度的第一天和最后一天
在SQL中,我可以得到以下内容
Select CURRENT_DATE as AS_OF_DT
,ADD_MONTHS(TRUNC(CURRENT_DATE,'Q'), -3) AS FIRST_DAY_OF_1ST_QUARTER
,ADD_MONTHS(TRUNC(CURRENT_DATE,'Q'), -2)-1 AS LAST_DAY_OF_1ST_QUARTER
,TO_VARCHAR(FIRST_DAY_OF_1ST_QUARTER,'YYYYMM') AS FIRST_MONTH
,ADD_MONTHS(TRUNC(CURRENT_DATE,'Q'), -2) AS FIRST_DAY_OF_2ND_QUARTER
,ADD_MONTHS(TRUNC(CURRENT_DATE,'Q'), -1)-1 AS LAST_DAY_OF_2ND_QUARTER
,TO_VARCHAR(FIRST_DAY_OF_2ND_QUARTER,'YYYYMM') AS SECOND_MONTH
,ADD_MONTHS(TRUNC(CURRENT_DATE,'Q'), -1) AS FIRST_DAY_OF_3RD_QUARTER
,TRUNC (CURRENT_DATE,'Q')- 1 AS LAST_DAY_OF_3RD_QUARTER
,TO_VARCHAR(FIRST_DAY_OF_3RD_QUARTER,'YYYYMM') AS THIRD_MONTH
,TO_VARCHAR(FIRST_DAY_OF_1ST_QUARTER,'YYYY') AS YEAR;
需要获得类似Python的输出
我尝试了如下基本功能
from datetime import datetime
from dateutil.relativedelta import relativedelta
current_date = datetime.now()
currQuarter = int((current_date.month - 1) / 3 + 1)
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = dtFirstDay + relativedelta(months=3, days=-1)
答案 0 :(得分:1)
由于qrt的第一天始终在1月,最后一天在3月,依此类推。计算所需日期非常简单
>>> from dateutil.relativedelta import relativedelta
>>> import datetime as dt
>>> dt.date.today()+relativedelta(months=3,day=1)
datetime.date(2021, 2, 1)
>>> dt.date.today()+relativedelta(month=4,day=1)
datetime.date(2020, 4, 1)
>>> dt.date.today()+relativedelta(month=3,day=31)
datetime.date(2020, 3, 31)
>>> for i in range(1,12,3):
... dt.date.today()+relativedelta(month=i,day=1)
... dt.date.today()+relativedelta(month=i+2,day=31)
...
datetime.date(2020, 1, 1)
datetime.date(2020, 3, 31)
datetime.date(2020, 4, 1)
datetime.date(2020, 6, 30)
datetime.date(2020, 7, 1)
datetime.date(2020, 9, 30)
datetime.date(2020, 10, 1)
datetime.date(2020, 12, 31)
编辑:
以下代码将两个日期都作为一个元组返回。我尚未对其进行广泛的测试,但是如果没有给出示例,它应该可以工作,所以我可以修补
import datetime as dt
from dateutil.relativedelta import relativedelta
def gen_last_and_first(dat):
first=[]
last=[]
for i in range(1,12,3):
first.append(dat+relativedelta(month=i,day=1))
last.append(dat+relativedelta(month=i+2,day=31))
return first, last
def pre_qrt(d=dt.date.today()):
date_sub=d+relativedelta(months=-3)
first, last=gen_last_and_first(date_sub)
first.sort(reverse=True)
for i in first:
if i<=date_sub:
first_day=i
break
last.sort()
for i in last:
if i>=date_sub:
last_day=i
break
return first_day, last_day
pre_qrt
是您要寻找的功能。默认情况下,它以当前日期为参考点。