python中的时间、日期操作——datetime

这篇博客详细介绍了如何使用Python的datetime模块进行日期和时间操作,包括获取今天、昨天、明天的日期,本周、上周、本月、上月、本季、上季及本年和去年的第一天和最后一天的方法。通过`calendar.monthrange()`函数,可以得到月份的首日星期和总天数等关键信息。
部署运行你感兴趣的模型镜像

导包:

import calendar
import datetime
from datetime import timedelta

获取今天日期:

#返回datetime格式:eg:2019-12-07 20:38:35.82816
now = datetime.datetime.now()

#返回datetime格式:eg:2019-12-07
now = datetime.datetime.now().date()
now = datetime.date.today()

获取昨天日期:

yesterday = now - timedelta(days=1)

获取明天日期:

tomorrow = now + timedelta(days=1)

获取本周第一天和最后一天:

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

获取上周第一天和最后一天:

last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)

获取本月第一天和最后一天:

this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])

注:
calendar.monthrange(year,month)
传入两个值:一个是当前的年份,另外一个是当前的月份
写法可以是:calendar.monthrange(now.year,now.month)
返回两个整数。
第一个值为该月第一天所在的星期几,对应的数字。0 - 6==>0(星期一)到6(星期日)
第二个值为该月一共几天。

获取上月第一天和最后一天 :

last_month_end = this_month_start - timedelta(days=1) 
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)

获取本季第一天和最后一天:

month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_start = datetime.datetime(now.year, month, 1)
this_quarter_end = datetime.datetime(now.year, month, calendar.monthrange(now.year, now.month)[1]) 

获取上季第一天和最后一天:

last_quarter_end = this_quarter_start - timedelta(days=1)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)

获取本年第一天和最后一天:

this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)

获取去年第一天和最后一天:

last_year_end = this_year_start - timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1) 

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值