python date of the previous month

前端 未结 12 1289
耶瑟儿~
耶瑟儿~ 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:35

    datetime and the datetime.timedelta classes are your friend.

    1. find today.
    2. use that to find the first day of this month.
    3. use timedelta to backup a single day, to the last day of the previous month.
    4. print the YYYYMM string you're looking for.

    Like this:

     import datetime
     today = datetime.date.today()
     first = today.replace(day=1)
     lastMonth = first - datetime.timedelta(days=1)
     print(lastMonth.strftime("%Y%m"))
    

    201202 is printed.

    0 讨论(0)
  • 2020-11-29 17:36

    You should use dateutil. With that, you can use relativedelta, it's an improved version of timedelta.

    >>> import datetime 
    >>> import dateutil.relativedelta
    >>> now = datetime.datetime.now()
    >>> print now
    2012-03-15 12:33:04.281248
    >>> print now + dateutil.relativedelta.relativedelta(months=-1)
    2012-02-15 12:33:04.281248
    
    0 讨论(0)
  • 2020-11-29 17:36
    def prev_month(date=datetime.datetime.today()):
        if date.month == 1:
            return date.replace(month=12,year=date.year-1)
        else:
            try:
                return date.replace(month=date.month-1)
            except ValueError:
                return prev_month(date=date.replace(day=date.day-1))
    
    0 讨论(0)
  • 2020-11-29 17:36

    Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)

    year = today.year
    month = today.month
    
    nm = list(divmod(year * 12 + month + 1, 12))
    if nm[1] == 0:
        nm[1] = 12
        nm[0] -= 1
    pm = list(divmod(year * 12 + month - 1, 12))
    if pm[1] == 0:
        pm[1] = 12
        pm[0] -= 1
    
    next_month = nm
    previous_month = pm
    
    0 讨论(0)
  • 2020-11-29 17:36

    If you want to look at the ASCII letters in a EXE type file in a LINUX/UNIX Environment, try "od -c 'filename' |more"

    You will likely get a lot of unrecognizable items, but they will all be presented, and the HEX representations will be displayed, and the ASCII equivalent characters (if appropriate) will follow the line of hex codes. Try it on a compiled piece of code that you know. You might see things in it you recognize.

    0 讨论(0)
  • 2020-11-29 17:37

    There is a high level library dateparser that can determine the past date given natural language, and return the corresponding Python datetime object

    from dateparser import parse
    parse('4 months ago')
    
    0 讨论(0)
提交回复
热议问题