python date of the previous month

前端 未结 12 1288
耶瑟儿~
耶瑟儿~ 2020-11-29 17:05

I am trying to get the date of the previous month with python. Here is what i\'ve tried:

str( time.strftime(\'%Y\') ) + str( int(time.strftime(\'%m\'))-1 )
<         


        
相关标签:
12条回答
  • 2020-11-29 17:19

    Building off the comment of @J.F. Sebastian, you can chain the replace() function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.

    from datetime import datetime, timedelta
    
    d = datetime(2012, 3, 31) # A problem date as an example
    
    # last day of last month
    one_month_ago = (d.replace(day=1) - timedelta(days=1))
    try:
        # try to go back to same day last month
        one_month_ago = one_month_ago.replace(day=d.day)
    except ValueError:
        pass
    print("one_month_ago: {0}".format(one_month_ago))
    

    Output:

    one_month_ago: 2012-02-29 00:00:00
    
    0 讨论(0)
  • 2020-11-29 17:20

    Building on bgporter's answer.

    def prev_month_range(when = None): 
        """Return (previous month's start date, previous month's end date)."""
        if not when:
            # Default to today.
            when = datetime.datetime.today()
        # Find previous month: https://stackoverflow.com/a/9725093/564514
        # Find today.
        first = datetime.date(day=1, month=when.month, year=when.year)
        # Use that to find the first day of this month.
        prev_month_end = first - datetime.timedelta(days=1)
        prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
        # Return previous month's start and end dates in YY-MM-DD format.
        return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))
    
    0 讨论(0)
  • 2020-11-29 17:23
    from datetime import date, timedelta
    
    first_day_of_current_month = date.today().replace(day=1)
    last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
    
    print "Previous month:", last_day_of_previous_month.month
    

    Or:

    from datetime import date, timedelta
    
    prev = date.today().replace(day=1) - timedelta(days=1)
    print prev.month
    
    0 讨论(0)
  • 2020-11-29 17:25

    For someone who got here and looking to get both the first and last day of the previous month:

    from datetime import date, timedelta
    
    last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
    
    start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
    
    # For printing results
    print("First day of prev month:", start_day_of_prev_month)
    print("Last day of prev month:", last_day_of_prev_month)
    

    Output:

    First day of prev month: 2019-02-01
    Last day of prev month: 2019-02-28
    
    0 讨论(0)
  • 2020-11-29 17:28

    Its very easy and simple. Do this

    from dateutil.relativedelta import relativedelta
    from datetime import datetime
    
    today_date = datetime.today()
    print "todays date time: %s" %today_date
    
    one_month_ago = today_date - relativedelta(months=1)
    print "one month ago date time: %s" % one_month_ago
    print "one month ago date: %s" % one_month_ago.date()
    

    Here is the output: $python2.7 main.py

    todays date time: 2016-09-06 02:13:01.937121
    one month ago date time: 2016-08-06 02:13:01.937121
    one month ago date: 2016-08-06
    
    0 讨论(0)
  • 2020-11-29 17:34

    With the Pendulum very complete library, we have the subtract method (and not "subStract"):

    import pendulum
    today = pendulum.datetime.today()  # 2020, january
    lastmonth = today.subtract(months=1)
    lastmonth.strftime('%Y%m')
    # '201912'
    

    We see that it handles jumping years.

    The reverse equivalent is add.

    https://pendulum.eustace.io/docs/#addition-and-subtraction

    0 讨论(0)
提交回复
热议问题