Formatting “yesterday's” date in python

后端 未结 6 2094
难免孤独
难免孤独 2020-12-02 03:56

I need to find \"yesterday\'s\" date in this format MMDDYY in Python.

So for instance, today\'s date would be represented like this: 111009

I ca

相关标签:
6条回答
  • 2020-12-02 04:36

    Use datetime.timedelta()

    >>> from datetime import date, timedelta
    >>> yesterday = date.today() - timedelta(days=1)
    >>> yesterday.strftime('%m%d%y')
    '110909'
    
    0 讨论(0)
  • 2020-12-02 04:39

    To expand on the answer given by Chris

    if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

    >>> from datetime import date, timedelta                   
    >>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
    >>> yesterday
    '020817'
    

    If you want it as an integer (which can be useful)

    >>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
    >>> yesterday
    20817
    
    0 讨论(0)
  • 2020-12-02 04:54

    Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?

    from datetime import datetime, timedelta
    
    yesterday = datetime.now() - timedelta(days=1)
    yesterday.strftime('%Y-%m-%d')
    
    0 讨论(0)
  • 2020-12-02 04:58

    This should do what you want:

    import datetime
    yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
    print yesterday.strftime("%m%d%y")
    
    0 讨论(0)
  • 2020-12-02 04:58

    all answers are correct, but I want to mention that time delta accepts negative arguments.

    >>> from datetime import date, timedelta
    >>> yesterday = date.today() + timedelta(days=-1)
    >>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses 
    
    0 讨论(0)
  • 2020-12-02 05:00
    from datetime import datetime, timedelta
    
    yesterday = datetime.now() - timedelta(days=1)
    yesterday.strftime('%m%d%y')
    
    0 讨论(0)
提交回复
热议问题