finding first day of the month in python

后端 未结 11 897
挽巷
挽巷 2021-02-02 05:39

I\'m trying to find the first day of the month in python with one condition: if my current date passed the 25th of the month, then the first date variable will hold the first da

11条回答
  •  囚心锁ツ
    2021-02-02 05:52

    Yes, first set a datetime to the start of the current month.

    Second test if current date day > 25 and get a true/false on that. If True then add add one month to the start of month datetime object. If false then use the datetime object with the value set to the beginning of the month.

    import datetime 
    from dateutil.relativedelta import relativedelta
    
    todayDate = datetime.date.today()
    resultDate = todayDate.replace(day=1)
    
    if ((todayDate - resultDate).days > 25):
        resultDate = resultDate + relativedelta(months=1)
    
    print resultDate
    

提交回复
热议问题