Python中可以使用datetime模块来获取每周、每月、季度、六个月、一年等的第一次和最后一次观察的日期。
import datetime
today = datetime.date.today()
start_of_week = today - datetime.timedelta(days=today.weekday())
end_of_week = start_of_week + datetime.timedelta(days=6)
print("本周第一天:", start_of_week)
print("本周最后一天:", end_of_week)
import datetime
today = datetime.date.today()
start_of_month = datetime.date(today.year, today.month, 1)
end_of_month = datetime.date(today.year, today.month+1, 1) - datetime.timedelta(days=1)
print("本月第一天:", start_of_month)
print("本月最后一天:", end_of_month)
import datetime
today = datetime.date.today()
quarter = (today.month - 1) // 3 + 1
start_of_quarter = datetime.date(today.year, 3 * quarter - 2, 1)
end_of_quarter = datetime.date(today.year, 3 * quarter, 1) - datetime.timedelta(days=1)
print("本季度第一天:", start_of_quarter)
print("本季度最后一天:", end_of_quarter)
import datetime
today = datetime.date.today()
start_of_six_months = datetime.date(today.year, today.month - 5, 1)
end_of_six_months = datetime.date(today.year, today.month + 1, 1) - datetime.timedelta(days=1)
print("过去六个月第一天:", start_of_six_months)
print("过去六个月最后一天:", end_of_six_months)
import datetime
today = datetime.date.today()
start_of_year = datetime.date(today.year, 1, 1)
end_of_year = datetime.date(today.year, 12, 31)
print("本年第一天:", start_of_year)
print("本年最后一天:", end_of_year)
以上代码可以根据当前日期动态计算出相应的日期范围。对于更复杂的日期计算,可以使用datetime模块提供的各种方法和属性进行处理。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云