Python如何计算从下月初开始算起38天后的对应截止日期
发票付款到期日计算规则及实现
示例场景
假设invoice_date = 09/11/2021,若付款周期为38天,则周期需从2021年12月1日开始计算,至2022年1月7日结束(12月共有31天),即due_date 为2022年1月7日。
通用规则
- 无论
invoice_date(发票日期)为当月任意日期,付款周期均需从下一个自然月的1号开始计算 - due_date(截止日期)为该起始日算起的第38天
Python 代码实现参考
import datetime def calculate_due_date(invoice_date: datetime.date, payment_cycle: int = 38) -> datetime.date: # 计算下一个自然月的1号 if invoice_date.month == 12: next_month_first = datetime.date(invoice_date.year + 1, 1, 1) else: next_month_first = datetime.date(invoice_date.year, invoice_date.month + 1, 1) # 加上付款周期天数得到到期日 return next_month_first + datetime.timedelta(days=payment_cycle) # 测试用例(对应示例场景) if __name__ == "__main__": # 09/11/2021 对应 datetime 格式为年-月-日:2021-11-09 invoice_date_sample = datetime.date(2021, 11, 9) due_date_sample = calculate_due_date(invoice_date_sample) # 输出结果:07/01/2022,与示例预期一致 print(due_date_sample.strftime("%d/%m/%Y")) # 获取当前日期的参考写法 today = datetime.date.today()
内容的提问来源于stack exchange,提问作者VEERA BABU
相关产品推荐
相关产品推荐

