自动化测试常用脚本-获取日期加减之后的日期

# 获取日期加减之后的日期方法一
from datetime import date, timedelta


def get_date(day_off):
    """
    if n>=0,date is larger than today
    if n<0,date is less than today
    date format = "YYYY-MM-DD"
    :param day_off: 日期差
    """
    if day_off < 0:
        day_off = abs(day_off)  # 若是获取距离当前日期之前 day_off 天的日期,先用 abs 将天数转换为绝对值
        return date.today() - timedelta(days=day_off) # timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, )
    else:
        return date.today() + timedelta(days=day_off)


if __name__ == '__main__':
    print(get_date(30))

 

# 获取日期加减之后的日期方法二

'''日期加减'''

def date_add_days(date, days):
    date1 = time.strptime(date, "%Y-%m-%d") # time.strptime()根据指定的格式把一个时间字符串解析为时间元组
    now = datetime.datetime(date1[0], date1[1], date1[2]) # 
    delta = datetime.timedelta(days=days)
    n_days = now + delta
    return n_days.strftime('%Y-%m-%d')

 

posted @ 2019-09-28 23:47  chenzy01  阅读(374)  评论(0编辑  收藏  举报