背景
我正在尝试注入一个有效负载,其中包含最近一个财政季度的日期。
示例
如果今天是4月20日(这是Q2中的一个日期),则最近完成的上一季度将是Q1(即1月1日至3月31日),因此我将向有效负载注入 * start_date: 2022-12-31
和end_date: 2023-03-31
。
*请注意start_date
始终为季度开始之前的日期;这是正常的做法。
当前编码
# I am currently injecting the current dates into my payload.
# Instead, I am looking for the previous quarter's dates
start_date = dt.datetime.today().strftime("%Y-%m-%d")
end_date = dt.datetime.today().strftime("%Y-%m-%d")
def job_initializer():
# calling function that returns variables required for API call
key, secret, url = authentication()
payload = """
{
"data":{
"type":"jobs",
"attributes":{
"job_type":"portfolio_view_results",
"parameters":{
"view_id":"416555",
"portfolio_type":"firm",
"portfolio_id":"1",
"output_type":"csv",
"start_date":"%s",
"end_date":"%s"
}
}
}
}
""" % (start_date, end_date)
建议
我看到很多10年前的历史帖子,但是我希望这可以使用pandas
或其他以时间为中心的python库来实现?
2条答案
按热度按时间e0bqpujr1#
numpy或其他库中可能内置了一些东西,但由于只有四个四分之一,因此没有太多的硬编码:
g9icjywg2#
您可以将季度的开始日期硬编码为
datetime
对象,例如Mark shows in their answer,将其硬编码为指定年偏移量、月和日的元组。给定
today = dt.date.today()
,该列表中当前季度的开始日期的索引为(today.month - 1 // 3)
。结束日期的索引为1加上开始日期索引:要在列
df["Date"]
中包含datetime对象的pandas Dataframe (df
)中使用这种方法,回想一下pandas提供了一个Series.dt.quarter
,它为任何日期提供i_start + 1
。让我们修改quarters
,以便我们可以在pandas向量函数中使用它:quarters_df
看起来像这样:然后,您可以执行以下操作:
**注意:**你也可以使用上面的公式来得到
i_start
和i_end
,但是我们有dt.quarter
,为什么不使用它:)最后,构建datetime列:
对于以下示例dataframe:
上面显示的方法为我们提供: