import datetime, time
from dateutil.relativedelta import relativedelta
# 执行pip install python-dateutil 安装python-dateutil模块,进行日期的加减处理
#relativedelta(years=+1, months=+1, days=+1,hours=+1, minutes=+1, seconds=+1),可进行不同维度时间的加减
# 与当前相差天数
def get_diff_days_2_now(date_str):
now_time = time.localtime(time.time())
compare_time = time.strptime(date_str, "%Y-%m-%d")
# 比较日期
date1 = datetime.datetime(compare_time[0], compare_time[1], compare_time[2])
date2 = datetime.datetime(now_time[0], now_time[1], now_time[2])
diff_days = (date2 - date1).days
# 上面是正确的获取方法,返回一个int类型天差值,修改时间:2019年8月25日
# diff_days = str(date2 - date1)
# # 如果相差0天单纯显示为 00:00:00 不然显示为 [diff_days] : 00:00:00
# diff_days_arr = diff_days.split(":")
# if len(diff_days_arr) == 1:
# return 0
# else:
# return diff_days_arr[0].split()[0]
return diff_days
# 获得指定差值的某一天
def get_specified_date(date, diff):
# 字符串转日期
sdate = datetime.datetime.strptime(date, '%Y-%m-%d')
# 加上指定的天数,可以为负
#
delta = sdate + relativedelta(days=diff)
# 日期转为字符串
specified_date = delta.strftime("%Y-%m-%d")
return specified_date
# 获得指定差值的某月
def get_specified_month(date, diff):
sdate = datetime.datetime.strptime(date, '%Y-%m-%d')
# 加上指定的月数,可以为负
delta = sdate + relativedelta(months=diff)
specified_date = delta.strftime("%Y-%m-%d")
return specified_date
# 获得指定差值的某月
def get_specified_year(date, diff):
sdate = datetime.datetime.strptime(date, '%Y-%m-%d')
# 加上指定的年数,可以为负
delta = sdate + relativedelta(years=diff)
specified_date = delta.strftime("%Y-%m-%d")
return specified_date