Python常用(日期、字符串等)小方法

Python常用(日期、字符串等)小方法

1、日期转换

    #21号之后的改为下月1号
    if int(bizDate.split("-")[2])>=21:
        year=int(bizDate.split("-")[0])
        month=int(bizDate.split("-")[1])
        if month == 12:
            nextmonth = 1
            nextyear = year+1
        else:
            nextmonth = month + 1
            nextyear=year
        if nextmonth<10:
            ywDate = str(nextyear)+'-0'+str(nextmonth)+'-01'
        else:
            ywDate = str(nextyear)+'-'+str(nextmonth)+'-01'
    else:
        ywDate=bizDate

 2、关于import datetime 的日期用法

today=datetime.date.today() #只取日期
strday=today.strftime("%Y%m") #日期转字符串
print(f"当前日期时间: {today},strday:{strday}") year=today.year month=today.month lastmonth=month-1 lastyear=year if month==1: lastmonth=12 lastyear=year-1 sdate=datetime.datetime.strptime(f"{lastyear}-{lastmonth}-01", "%Y-%m-%d").date() #字符串转日期 edate=datetime.datetime.strptime(f"{year}-{month}-01", "%Y-%m-%d").date()-datetime.timedelta(days=1) print(f"开始日期:{sdate},结束日期:{edate}")

 

posted @ 2025-06-17 14:33  中国结  阅读(8)  评论(0)    收藏  举报