What's the simplest way to subtract a month from a date in Python?

前端 未结 21 1915
[愿得一人]
[愿得一人] 2020-12-02 09:12

If only timedelta had a month argument in it\'s constructor. So what\'s the simplest way to do this?

EDIT: I wasn\'t thinking too hard about this as was poin

21条回答
  •  天命终不由人
    2020-12-02 09:38

    I Used the following code to go back n Months from a specific Date:

    your_date =  datetime.strptime(input_date, "%Y-%m-%d")  #to convert date(2016-01-01) to timestamp
    start_date=your_date    #start from current date
    
    #Calculate Month
    for i in range(0,n):    #n = number of months you need to go back
        start_date=start_date.replace(day=1)    #1st day of current month
        start_date=start_date-timedelta(days=1) #last day of previous month
    
    #Calculate Day
    if(start_date.day>your_date.day):   
        start_date=start_date.replace(day=your_date.day)            
    
    print start_date
    

    For eg: input date = 28/12/2015 Calculate 6 months previous date.

    I) CALCULATE MONTH: This step will give you the start_date as 30/06/2015.
    Note that after the calculate month step you will get the last day of the required month.

    II)CALCULATE DAY: Condition if(start_date.day>your_date.day) checks whether the day from input_date is present in the required month. This handles condition where input date is 31(or 30) and the required month has less than 31(or 30 in case of feb) days. It handles leap year case as well(For Feb). After this step you will get result as 28/06/2015

    If this condition is not satisfied, the start_date remains the last date of the previous month. So if you give 31/12/2015 as input date and want 6 months previous date, it will give you 30/06/2015

提交回复
热议问题