在Python中获取过去四个月的第一个和最后一个日期,可以使用datetime模块来实现。
首先,导入datetime模块:
import datetime
然后,获取当前日期:
current_date = datetime.date.today()
接下来,计算过去四个月的日期。由于每个月的天数不同,我们需要处理一些特殊情况。首先,获取当前日期的年份和月份:
current_year = current_date.year
current_month = current_date.month
然后,计算过去四个月的年份和月份。如果当前月份大于四个月,则直接减去四个月;否则,需要向前借一年,并加上剩余的月份:
if current_month > 4:
past_year = current_year
past_month = current_month - 4
else:
past_year = current_year - 1
past_month = current_month + 8
接着,获取过去四个月的第一个日期。我们可以使用datetime模块中的date类来表示日期,通过指定年份、月份和日期来创建一个日期对象:
past_first_date = datetime.date(past_year, past_month, 1)
最后,获取过去四个月的最后一个日期。我们可以使用calendar模块来获取指定年份和月份的最后一天:
import calendar
_, last_day = calendar.monthrange(past_year, past_month)
past_last_date = datetime.date(past_year, past_month, last_day)
完整的代码如下:
import datetime
import calendar
current_date = datetime.date.today()
current_year = current_date.year
current_month = current_date.month
if current_month > 4:
past_year = current_year
past_month = current_month - 4
else:
past_year = current_year - 1
past_month = current_month + 8
past_first_date = datetime.date(past_year, past_month, 1)
_, last_day = calendar.monthrange(past_year, past_month)
past_last_date = datetime.date(past_year, past_month, last_day)
print("过去四个月的第一个日期:", past_first_date)
print("过去四个月的最后一个日期:", past_last_date)
这样,你就可以在Python中获取过去四个月的第一个和最后一个日期了。
云+社区技术沙龙[第6期]
腾讯技术创作特训营
TC-Day
TC-Day
云+社区技术沙龙[第27期]
云+社区技术沙龙[第7期]
腾讯云GAME-TECH沙龙
云+社区技术沙龙[第1期]
领取专属 10元无门槛券
手把手带您无忧上云