datetime、calendar 获取日期的使用样例

复制代码
import datetime

dt = datetime.datetime
print(dt)
dt = dt.now()
print(dt)
dt = dt.date()
print(dt)
dt = dt + datetime.timedelta(days=1)
print(dt)
复制代码

 

先导入包:

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) 

 

 

 

posted @    ̄□ ̄  阅读(222)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示