首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python -获取每周、每月、季度、六个月、一年等的第一次和最后一次观察

Python中可以使用datetime模块来获取每周、每月、季度、六个月、一年等的第一次和最后一次观察的日期。

  1. 获取每周的第一天和最后一天:
代码语言:txt
复制
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)
  1. 获取每月的第一天和最后一天:
代码语言:txt
复制
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)
  1. 获取每个季度的第一天和最后一天:
代码语言:txt
复制
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)
  1. 获取六个月的第一天和最后一天:
代码语言:txt
复制
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)
  1. 获取一年的第一天和最后一天:
代码语言:txt
复制
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模块提供的各种方法和属性进行处理。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云函数计算(云原生):https://cloud.tencent.com/product/scf
  • 腾讯云数据库(数据库):https://cloud.tencent.com/product/cdb
  • 腾讯云服务器(服务器运维):https://cloud.tencent.com/product/cvm
  • 腾讯云对象存储(存储):https://cloud.tencent.com/product/cos
  • 腾讯云人工智能(人工智能):https://cloud.tencent.com/product/ai
  • 腾讯云物联网(物联网):https://cloud.tencent.com/product/iotexplorer
  • 腾讯云移动开发(移动开发):https://cloud.tencent.com/product/mobdev
  • 腾讯云区块链(区块链):https://cloud.tencent.com/product/baas
  • 腾讯云视频处理(音视频、多媒体处理):https://cloud.tencent.com/product/vod
  • 腾讯云网络安全(网络安全):https://cloud.tencent.com/product/ddos
  • 腾讯云CDN加速(网络通信):https://cloud.tencent.com/product/cdn
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券