import datetime, calendar
'''
# python取下个月月份
def month_1():
now_time = datetime.datetime.now()
week, days_num = calendar.monthrange(now_time.year, now_time.month)
print(week, days_num)
end_day_in_mouth = now_time.replace(day=days_num)
next_mouth = end_day_in_mouth + datetime.timedelta(days=1)
return end_day_in_mouth.day, next_mouth.month
# python取上个月月份
def month_2():
now_time = datetime.datetime.now()
end_day_in_mouth = now_time.replace(day=1)
next_mouth = end_day_in_mouth - datetime.timedelta(days=1)
return next_mouth.month, next_mouth.day
month_last_day = month_1()[0] # 本月最后一天
next_month = month_1()[1] # 下月月份
# next_month_last_day = month_1()[2] # 下月最后一天
last_month = month_2()[0] # 上月月份
# last_month_last_day = month_2()[1] # 上月最后一天
print(month_last_day)
print(next_month)
# print(next_month_last_day)
print(last_month)
# print(last_month_last_day)
'''
# 当前时间,月,天,第一天,最后一天
time = datetime.datetime.now()
month = time.month
day = time.day
print('当前月份:', month)
print('当前天:', day)
first_day_month = datetime.date(time.year, time.month, 1)
print('当前月的第一天:' + str(first_day_month))
days_num = calendar.monthrange(first_day_month.year, first_day_month.month)[1] # 获取当前月有多少天
last_day_month = first_day_month + datetime.timedelta(days=days_num - 1)
print('当前月最后一天:' + str(last_day_month))
# 上月月份、最后一天、第一天
last_month_last_day = first_day_month - datetime.timedelta(days=1) # timedelta是一个不错的函数
last_month = last_month_last_day.month
print('上月月份', last_month)
print('上月最后一天:' + str(last_month_last_day))
last_month_first_day = datetime.date(last_month_last_day.year, last_month_last_day.month, 1)
print('上月第一天:' + str(last_month_first_day))
# 下月月份、第一天、最后一天
next_month_first_day = first_day_month + datetime.timedelta(days=days_num)
next_month = next_month_first_day.month
print('下月月份', next_month)
print('下个月的第一天:' + str(next_month_first_day))
next_month_days = calendar.monthrange(next_month_first_day.year, next_month_first_day.month)[1] # 获取下个月有多少天
next_month_last_day = next_month_first_day + datetime.timedelta(days=next_month_days - 1)
print('下个月最后一天:' + str(next_month_last_day))
# 上两月月份、第一天、最后一天
last_2_month_last_day = last_month_first_day - datetime.timedelta(days=1)
last_2_month = last_2_month_last_day.month
print('上两月月份', last_2_month)
last_2_month_first_day = datetime.date(last_2_month_last_day.year, last_2_month_last_day.month, 1)
print('上两月的第一天:' + str(last_2_month_first_day))
# 如果当前日小于14号,则更新上月数据,如果当前月大于等于15号,则更新当月数据
if day < 14:
date_start = last_2_month_first_day # 上两月第一天
date_end = last_day_month # 本月最后一天
else:
date_start = last_month_first_day # 上月第一天
date_end = next_month_last_day # 下月最后一天
print(date_start, date_end)