Python实现日期判断和加减操作详解
作者:幸福的达哥 发布时间:2021-06-17 09:20:02
标签:Python,日期,判断,加减
python实现日期判断和加减操作
#====================================================
#时间相关
#====================================================
def if_workday(day_str, separator=""):
"""
if a day is workday
:param day_str: string of a day
:param separator: separator of year, month and day, default is empty
:return: True: is workday; False: not workday
"""
spec = "%Y" + separator + "%m" + separator + "%d"
day = datetime.strptime(day_str, spec).date()
# Monday == 0 ... Sunday == 6
if day.weekday() in [0, 1, 2, 3, 4]:
return True
else:
return False
def if_weekend(day_str, separator=""):
"""
if a day is weekend
:param day_str: string of a day
:param separator: separator of year, month and day, default is empty
:return: True: is weekend; False: not weekend
"""
spec = "%Y" + separator + "%m" + separator + "%d"
day = datetime.strptime(day_str, spec).date()
# Monday == 0 ... Sunday == 6
if day.weekday() in [5, 6]:
return True
else:
return False
def is_week_lastday():
'''
判断今天是否为周末,return the day of the week as an integer,Monday is 0 and Sunday is 6
:return:
'''
now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
# 假如今天是周日
todayIndex = now.weekday()
# 如果今天是周日,则返回True
if todayIndex == 6:
print("todayIndex={},今天是周末...".format(todayIndex))
return True
else:
print("todayIndex={},今天是周 {},不是周末...".format(todayIndex,int(todayIndex+1)))
return False
def is_week_whichday(dayIndex=6):
'''
判断今天一周的哪一天,周一为0,周末为6,return the day of the week as an integer,Monday is 0 and Sunday is 6
:return:
'''
now = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))
# 假如今天是周日
todayIndex = now.weekday()
# 如果今天是周日,则返回True
if todayIndex == dayIndex:
print("todayIndex={},今天是周 {},不是周 {}...".format(todayIndex, int(todayIndex+1),int(dayIndex+1)))
return True
else:
print("todayIndex={},今天是周 {},不是周 {}...".format(todayIndex,int(todayIndex+1),int(dayIndex+1)))
return False
def is_month_lastday():
'''
# 判断今天是否为月末
:return:
'''
# 获得当月1号的日期
start_date = datetime.date.today().replace(day=1)
# 获得当月一共有多少天(也就是最后一天的日期)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
todayIndex = time.strftime("%d", time.localtime())
# 如果今天是周末,返回True
if int(todayIndex) == int(days_in_month):
print("start_date={},todayIndex={},days_in_month={},今天是月末...".format(start_date,todayIndex, days_in_month))
return True
else:
print("start_date={},todayIndex={},days_in_month={},今天不是月末...".format(start_date,todayIndex , days_in_month))
return False
def get_this_week_start():
'''
获取本周第一天日期
:return:
'''
now = datetime.datetime.now()
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6 - now.weekday())
print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
print('--- this_week_start = {} '.format(this_week_start))
return this_week_start
def get_this_week_end():
'''
# 获取本周最后一天日期
:return:
'''
now = datetime.datetime.now()
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6 - now.weekday())
print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))
print('--- this_week_end = {}'.format(this_week_end))
return this_week_end
def get_last_month_start(now = datetime.datetime.now()):
now = datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
print('--- last_month_start = {}'.format(last_month_start))
return last_month_start
def get_last_month_end(now = datetime.datetime.now()):
now = datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
print('--- last_month_end = {} '.format(last_month_end))
return last_month_end
def get_this_month_start(now = datetime.datetime.now()):
now = datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
print('--- this_month_start = {} '.format(this_month_start))
return this_month_start
def get_this_month_end(now = datetime.datetime.now()):
now=datetime.datetime.strptime(now, "%Y-%m-%d")
# 本月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
# this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
if now.month < 12:
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
elif now.month >= 12:
this_month_end = datetime.datetime(now.year, now.month , now.day+30) + datetime.timedelta(hours=23, minutes=59, seconds=59)
# print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))
# 上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1) + datetime.timedelta(hours=23, minutes=59, seconds=59)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
# print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))
# print('--- this_month_end = {} '.format(this_month_end))
return str(this_month_end)
#从一个时间段获取其中的每一天,可以自定义时间间隔
def get_every_day(start = '2018-01-01',end = '2021-01-01',daysCount=1):
'''
从一个时间段获取其中的每一天,可以自定义时间间隔
:param start: str类型,开始时间,如:'2018-01-01'
:param end: str类型,结束时间,如:'2021-01-01'
:param daysCount: int类型,每一个时间间隔,默认为1天
:return:
'''
datestart = datetime.datetime.strptime(start, '%Y-%m-%d')
dateend = datetime.datetime.strptime(end, '%Y-%m-%d')
date_list=[]
while datestart < dateend:
datestart += datetime.timedelta(days=daysCount)
date_str=str(datestart.strftime('%Y-%m-%d'))
# print('date_str={}'.format(date_str))
date_list.append(date_str)
print('date_list={}'.format(date_list))
return date_list
#从一个时间段获取其中的每一月,可以自定义时间间隔
def getBetweenEveryMonth(begin_date,end_date):
date_list = []
begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
# end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d")
while begin_date <= end_date:
date_str = begin_date.strftime("%Y-%m-%d")
begin_date = add_months_start(begin_date, 1)
date_end=get_this_month_end(date_str)
date_list.append((date_str+' 00:00:00',date_end))
print('date_list={}'.format(date_list))
return date_list
def add_months_start(dt, months):
month = int(dt.month - 1 + months)
year = int(dt.year + month / 12)
month = int(month % 12 + 1)
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)
def add_months_end(dt, months):
month = int(dt.month - 1 + months)
year = int(dt.year + month / 12)
month = int(month % 12 + 1)
day = max(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)
来源:https://blog.csdn.net/zh6526157/article/details/122431151


猜你喜欢
- 函数:split()例子我们想要将以下字符串rule进行拆分。字符串表示的是一个规则,由“…”得到“…”。我们需要将规则中的条件属性与取值分
- 题目:请求出任意区间[a,b]的所有素数,简单考虑实用性这道题看起来应该很easy是吧,但任意区间(这个问题有没get 到)Afanty的分
- 游标是 * 的!在关系数据库中,我们对于查询的思考是面向集合的。而游标打破了这一规则,游标使得我们思考方式变为逐行进行.对于类C的开发人员来着
- 目标网址:https://www.baidu.com/要获取的内容:链接分析:从下图可以看出只需要获取关键字,再构建就可以了。完整代码:im
- 前言只统计像素的灰度值这一特征,可将其成为一维直方图。二维直方图可以统计像素的色相和饱和度,用于查找图像的颜色直方图。一、OpenCV中的二
- MySQL的数据库管理工具非常多,有哪些优秀的GUI工具可以帮助提高工作效率?不妨看一看这5个MySQL GUI工具。1、Navicat f
- 0. 前言无论在工作中,还是学习中,都会出现这样子的需求,对某张表进行了排序(按时间排序也好,其他字段排序也罢),然后获取前x行的数据,由于
- 你可能在使用MySQL过程中,各种意外导致数据库表的损坏,而且这些数据往往是最新的数据,通常不可能在备份数据中找到。本章将讲述如何检测MyS
- 字符串字符串在Python中是基本数据类型,是一个不可变的字符序列。字符串驻留机制仅保存一份相同且不可变字符串的方法,不同的值被存放在字符串
- 在使用pytorch框架时,难免要自己定义网络。于是,super(XXXX, self).init(),就成了自定义网络结构时必不可少的第一
- 本文实例为大家分享JavaScript弹出拖拽窗口的具体实现代码,供大家参考,具体内容如下需求说明: 1、点击页面按钮,弹出窗口;
- BSQL Hacker10个SQL注入工具BSQL Hacker是由Portcullis实验室开发的,BSQL Hacker 是一个SQL自
- 一:threading VS Thread众所周知,python是支持多线程的,而且是native的线程,其中threading是对Thre
- 对于变量的访问和设置,我们可以使用get、set方法,如下:class student: def __init__(self,n
- Mysqli是php5之后才有的功能,没有开启扩展的朋友可以打开您的php.ini的配置文件。 查找下面的语句:;extension=php
- 关键路径计算是项目管理中关于进度管理的基本计算。 但是对于绝大多数同学来说, 关键路径计算都只是对一些简单情形的计算。今天,田老师根据以往的
- 引言继上一篇 《Blender Python 编程:快速入门》 我们已经了解了 Blender Python 脚本的基本概念。接下来让我们了
- 1.GridView无代码分页排序:效果图:1.AllowSorting设为True,aspx代码中是AllowSorting="
- 前言本文重点介绍 MySQL BIGINT 数据类型,并研究我们如何使用它来存储整数值。我们还将了解它的范围、存储大小和各种属性,包括有符号
- 本文实例讲述了Python实现爬虫抓取与读写、追加到excel文件操作。分享给大家供大家参考,具体如下:爬取糗事百科热门安装 读写excel