Python日期计算,你在哪里?
我有一个python应用程序,它需要在几年内每三个月绘制一次日期。重要的是日期在一年中恰好出现4次,并且日期尽可能出现在每年的同一天,日期尽可能出现在月份的同一天,并且日期尽可能地接近"3个月“(这是一个移动的目标,特别是在闰年)。不幸的是,datetime.timedelta不支持月份!
在python中有没有“标准”的计算方法?
SQL方式?
如果最坏的情况发生,我会用平底船,让我的应用程序向PostgreSQL询问,他确实有很好的内置日期计算支持,答案如下:
# select ('2010-11-29'::date + interval '3 months')::date;
date
------------
2011-02-28
(1 row)发布于 2020-12-28 21:34:22
我编写了这个函数,它可能会对您有所帮助:
import datetime
import calendar
def add_months(date, months):
# Determine the month and year of the new date
month, year = (date + relativedelta(months=months)).month, (date + relativedelta(months=months)).year
# Determine the day of the new date
# If the day of the current date is at the end of the month,
# the day of the new date should also be at the end of the month
if(date.day == calendar.monthrange(date.year, date.month)[1]):
day = calendar.monthrange(year, month)[1]
else:
day = date.day
new_date = datetime.datetime(year, month, day)
return new_date支持增加负数月份(即减去月份)。
以下是一些示例用法,说明如何根据您的规格获取2021年和2022年的日期:
import datetime
a = datetime.datetime(2020, 1, 1)
# Initialse a list to hold the dates
dates = [0]*8
# Obtain the dates
for i in range(0, len(dates)):
dates[i] = add_months(a, 3*i)
dateshttps://stackoverflow.com/questions/9594282
复制相似问题