from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta

#将yyyy月m月d日格式的日期转为yyyy-mm-dd格式的日期
def convertDate(sDate:str):
    sDate = sDate.replace("年","-")
    sDate = sDate.replace("月", "-")
    sDate = sDate.replace("日", "")
    date_obj = datetime.strptime(sDate, '%Y-%m-%d')
    sDate = date_obj.strftime('%Y-%m-%d')
    return sDate

#日期加减偏置，参数ymd为单位，y=年，m=月，d=日
def dateAdd(sDate:str,ymd:str="d",diff:int=1):
    if sDate=="":
        sDate = datetime.now()
        sDate = sDate.strftime('%Y-%m-%d')

    date_obj = datetime.strptime(sDate, '%Y-%m-%d')
    if ymd=="y":
        if diff > 0:
            date_obj = date_obj+relativedelta(years=diff)
        else:
            diff=-diff
            date_obj = date_obj - relativedelta(years=diff)
    elif ymd=="m":
        if diff>0:
            date_obj = date_obj + relativedelta(months=diff)
        else:
            diff=-diff
            date_obj = date_obj - relativedelta(months=diff)
    elif ymd=="d":
        date_obj = date_obj + timedelta(days=diff)
    else:
        pass
    sDate = date_obj.strftime('%Y-%m-%d')
    return sDate