finding first day of the month in python

后端 未结 11 1035
挽巷
挽巷 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:54

    This is a pithy solution.

    import datetime 
    
    todayDate = datetime.date.today()
    if todayDate.day > 25:
        todayDate += datetime.timedelta(7)
    print todayDate.replace(day=1)
    

    One thing to note with the original code example is that using timedelta(30) will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.

提交回复
热议问题