python计算本周周末日期_python获取本周、上周、本月、上月及本季的时间代码实例...

前言

本文主要介绍的是关于利用python 获取本周,上周,本月,上月,本季的时间,话不多说了,来一起看看实现的方法吧

示例代码:

import datetime

from datetime import timedelta

now = datetime.datetime.now()

# 今天

today = now

print('--- today = {}'.format(today))

# 昨天

yesterday = now - timedelta(days=1)

print('--- yesterday = {}'.format(yesterday))

# 明天

tomorrow = now + timedelta(days=1)

print('--- tomorrow = {}'.format(tomorrow))

# 当前季度

now_quarter = now.month / 3 if now.month % 3 == 0 else now.month / 3 + 1

print('--- now_quarter = {}'.format(now_quarter))

# 本周第一天和最后一天

this_week_start = now - timedelta(days=now.weekday())

this_week_end = now + timedelta(days=6 - now.weekday())

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Pythondatetime实现本周上周本月和上起止日期代码: ```python import datetime # 本周起止日期 now = datetime.datetime.now() start_of_week = now - datetime.timedelta(days=now.weekday()) end_of_week = start_of_week + datetime.timedelta(days=6) # 上周起止日期 start_of_last_week = start_of_week - datetime.timedelta(days=7) end_of_last_week = end_of_week - datetime.timedelta(days=7) # 本月起止日期 start_of_month = datetime.datetime(now.year, now.month, 1) if now.month == 12: end_of_month = datetime.datetime(now.year+1, 1, 1) - datetime.timedelta(days=1) else: end_of_month = datetime.datetime(now.year, now.month+1, 1) - datetime.timedelta(days=1) # 上起止日期 last_month = now.month - 1 if now.month > 1 else 12 last_year = now.year - 1 if last_month == 12 else now.year start_of_last_month = datetime.datetime(last_year, last_month, 1) end_of_last_month = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(days=1) # 输出起止日期 print("本周起止日期:", start_of_week.date(), "-", end_of_week.date()) print("上周起止日期:", start_of_last_week.date(), "-", end_of_last_week.date()) print("本月起止日期:", start_of_month.date(), "-", end_of_month.date()) print("上起止日期:", start_of_last_month.date(), "-", end_of_last_month.date()) ``` 其中关键的方法是`datetime.timedelta()`表示时间差,例如`datetime.timedelta(days=7)`表示7天时间差。`datetime.datetime()`则表示一个具体的日期时间

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值