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)

到此这篇关于Python实现日期判断和加减操作详解的文章就介绍到这了,更多相关Python日期判断 加减操作内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python判断给定的字符串是否是有效日期的方法

    本文实例讲述了python判断给定的字符串是否是有效日期的方法.分享给大家供大家参考.具体分析如下: 这里python判断给定的字符串是否是一个有效的日期,如果是一个日期格式的字符串,该函数返回True,否则返回False def is_valid_date(str): '''判断是否是一个有效的日期字符串''' try: time.strptime(str, "%Y-%m-%d") return True except: return False 希望本文所述对大家的Python程序

  • Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年

    计算年.月.日需要安装组件包 pip install python-dateutil 当前日期时间 import datetime print datetime.datetime.now() # 2018-05-08 16:53:30.101000 格式化时间 import datetime print datetime.datetime.now().strftime("%Y-%m-%d %H:%M") # 2018-05-08 16:54 多加一天 import datetime p

  • Python日期的加减等操作的示例

    本文介绍了Python日期的加减等操作的示例,分享给大家,也给自己留个笔记 1. 日期输出格式化 所有日期.时间的api都在datetime模块内. 1. datetime => string now = datetime.datetime.now() now.strftime('%Y-%m-%d %H:%M:%S') #输出2012-03-05 16:26:23.870105 strftime是datetime类的实例方法. 2. string => datetime t_str = '20

  • python3 中时间戳、时间、日期的转换和加减操作

    1.当前时间戳转换为指定格式的日期 # -*- coding: utf-8 -*- # @Time : 2019/5/31 10:56 # @Author : 甄超锋 # @Email : 4535@sohu.com # @File : test.py # @Software: PyCharm import datetime import time # 使用time timeStamp = time.time() # 1559286774.2953627 timeArray = time.loc

  • python判断输入日期为第几天的实例

    如下所示: # -*- coding: utf-8 -*- # 简述:要求输入某年某月某日 # 提问:求判断输入日期是当年中的第几天? def which_day(year,month,day): list=[31,28,31,30,31,30,31,31,30,31,30,31] whichday=0 if (year%4)==0 and (year%100)!=0 or (year%400)==0: list[1]=29 for i in range(1,month): if month =

  • Python实现日期判断和加减操作详解

    python实现日期判断和加减操作 #==================================================== #时间相关 #==================================================== def if_workday(day_str, separator=""): """ if a day is workday :param day_str: string of a day :pa

  • Python必备技巧之字符数据操作详解

    目录 字符串操作 字符串 + 运算符 字符串 * 运算符 字符串 in 运算符 内置字符串函数 字符串索引 字符串切片 字符串切片中的步幅 将变量插入字符串 修改字符串 内置字符串方法 bytes对象 定义文字bytes对象 bytes使用内置bytes()函数定义对象 bytes对象操作,操作参考字符串. bytearray对象,Python 支持的另一种二进制序列类型 字符串操作 字符串 + 运算符 +运算符用于连接字符串,返回一个由连接在一起的操作数组成的字符串. >>> s =

  • 对python for 文件指定行读写操作详解

    1.os.mknod("test.txt") #创建空文件 2.fp = open("test.txt",w) #直接打开一个文件,如果文件不存在则创建文件 3.关于open 模式: 详情: w:以写方式打开, a:以追加模式打开 (从 EOF 开始, 必要时创建新文件) r+:以读写模式打开 w+:以读写模式打开 (参见 w ) a+:以读写模式打开 (参见 a ) rb:以二进制读模式打开 wb:以二进制写模式打开 (参见 w ) ab:以二进制追加模式打开 (

  • 基于Python对数据shape的常见操作详解

    这一阵在用python做DRL建模的时候,尤其是在配合使用tensorflow的时候,加上tensorflow是先搭框架再跑数据,所以调试起来很不方便,经常遇到输入数据或者中间数据shape的类型不统一,导致一些op老是报错.而且由于水平菜,所以一些常用的数据shape转换操作也经常百度了还是忘,所以想再整理一下. 一.数据的基本属性 求一组数据的长度 a = [1,2,3,4,5,6,7,8,9,10,11,12] print(len(a)) print(np.size(a)) 求一组数据的s

  • Python 分布式缓存之Reids数据类型操作详解

    1.Redis API 1.安装redis模块 $ pip3.8 install redis 2.使用redis模块 import redis # 连接redis的ip地址/主机名,port,password=None r = redis.Redis(host="127.0.0.1",port=6379,password="gs123456") 3.redis连接池 redis-py使用connection pool来管理对一个redis server的所有连接,避

  • Python+Selenium键盘鼠标模拟事件操作详解

    目录 元素的基本操作 鼠标键盘模拟事件操作 利用 Keys 模块模拟键盘操作事件 利用 Action 类模拟鼠标操作事件 当我们定位到具体的一个元素的时候就可以对这个元素进行具体的操作,比如之前章节所执行的 click 操作.这是最简单的操作,webdriver 还有其他的操作.比如元素的基本操作(点击.输入.清除),还有一些高级操作如鼠标键盘模拟事件.弹出框处理.多页面切换等… 这些都是需要我们了解的内容,也是在做自动化测试的时候经常遇到的一些基本场景.今天这一章节,我们就先来学习一下元素的基

  • Python Numpy中数组的集合操作详解

    我们知道两个 set 对象之间,可以取交集.并集.差集.对称差集,举个例子: s1 = {1, 2, 3} s2 = {2, 3, 4} """ &: 交集 |: 并集  -: 差集 ^: 对称差集 """ # 以下几种方式是等价的 # 但是一般我们都会使用操作符来进行处理,因为比较方便 print(s1 & s1) print(s1.intersection(s2)) print(set.intersection(s1, s2)

  • Python基于Tensor FLow的图像处理操作详解

    本文实例讲述了Python基于Tensor FLow的图像处理操作.分享给大家供大家参考,具体如下: 在对图像进行深度学习时,有时可能图片的数量不足,或者希望网络进行更多的学习,这时可以对现有的图片数据进行处理使其变成一张新的图片,在此基础上进行学习,从而提高网络识别的准确率. 1.图像解码显示 利用matplot库可以方便简洁地在jupyter内对图片进行绘制与输出,首先通过tf.gfile打开图片文件,并利用函数tf.image.decode_jpeg将jpeg图片解码为三位矩阵,之后便可以

  • 使用Python进行稳定可靠的文件操作详解

    考虑下述Python代码片段.对文件中的数据进行某些操作,然后将结果保存回文件中: 复制代码 代码如下: with open(filename) as f:   input = f.read()output = do_something(input)with open(filename, 'w') as f:   f.write(output) 看起来很简单吧?可能看起来并不像乍一看这么简单.我在产品服务器中调试应用,经常会出现奇怪的行为.这是我看过的失效模式的例子:失控的服务器进程溢出大量日志

随机推荐