finding first day of the month in python

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

    The arrow module will steer you around and away from subtle mistakes, and it's easier to use that older products.

    import arrow
    
    def cleanWay(oneDate):
        if currentDate.date().day > 25:
            return currentDate.replace(months=+1,day=1)
        else:
            return currentDate.replace(day=1)
    
    
    currentDate = arrow.get('25-Feb-2017', 'DD-MMM-YYYY')
    print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
    
    currentDate = arrow.get('28-Feb-2017', 'DD-MMM-YYYY')
    print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
    

    In this case there is no need for you to consider the varying lengths of months, for instance. Here's the output from this script.

    25-Feb-2017 01-Feb-2017
    28-Feb-2017 01-Mar-2017
    

提交回复
热议问题