【问题标题】:Calculate end of quarter dates计算季度结束日期
【发布时间】:2021-02-10 10:19:37
【问题描述】:

我正在尝试查找两个日期之间的所有季度结束日期。我还想使用当前/进行中季度的最长日期。

def calculate_quarters(start_yyyy_mm_dd, end_yyyy_mm_dd):
     ...
     ...
     ...

x = calculate_quarters('2020-01-01', '2021-01-07')
print(x)

> ['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31', '2021-01-07']

我查看了之前的一些答案,发现我们可以这样计算季度末:

>>> d = datetime.date.today()
>>> datetime.date(year=d.year, month=((d.month % 3) + 1) * 3 + 1, day=1) - datetime.timedelta(days=1)
datetime.date(2015, 9, 30)

但我不确定如何使其适应范围并处理不完整的季度。

【问题讨论】:

  • 添加'2021-01-07'的逻辑是什么?
  • 我不明白您的问题,但已根据原始问题进行了修改,希望能更清楚
  • 我不明白I would also like to use the maximum date for the current / in-progress quarter.,这意味着添加了结束日期时间?
  • 由于结束日期为 2021-01-07,它代表 2021 年第一季度,但 2021 年第一季度当前不完整,因为我们现在是 2 月。对于这种情况,我不想要季度结束日期,而是将 end_yyyy_mm_dd 作为当前季度的最大日期。

标签: python python-3.x pandas date


【解决方案1】:

如果只需要匹配两个日期之间的季度,则使用 period_range 表示季度,通过PeriodIndex.to_timestamp 转换为时间戳,通过DatetimeIndex.normalize 转换为时间戳,如果在Index.union 的范围内不存在,则最后添加最后一个不完整的结束时间戳:

def calculate_quarters(s, e):
    r = pd.period_range(s, e, freq='Q').to_timestamp(how='end').normalize()
    return r[(r > s) & (r < e)].union(pd.to_datetime([e])).strftime('%Y-%m-%d').tolist()


print (calculate_quarters('2020-01-01', '2021-01-07'))
['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31','2021-01-07']
               

def calculate_quarters(s, e):
    r = pd.period_range(s, e, freq='Q').to_timestamp(how='end').normalize()
    return r[(r > s) & (r < e)].union(pd.to_datetime([e])).strftime('%Y-%m-%d').tolist()


print (calculate_quarters('2020-01-01', '2020-12-31'))
['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31']

【讨论】:

  • 我建议将return 修改为:return (r[(r &gt; s) &amp; (r &lt; e)].union(pd.to_datetime([e]))).strftime('%Y-%m-%d').tolist()。这将产生一个字符串列表而不是 DatetimeIndex
猜你喜欢
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多