272

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 can easily do this for today but I have trouble doing it automatically for "yesterday".

kqw
  • 19,513
  • 11
  • 64
  • 96
y2k
  • 64,108
  • 26
  • 59
  • 85

6 Answers6

478

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
Boris Verkhovskiy
  • 10,733
  • 7
  • 77
  • 79
Jarret Hardie
  • 90,470
  • 10
  • 128
  • 124
  • 2
    If you happen to be working with pandas, you can as well use: `print((pd.to_datetime('Today') - pd.Timedelta('1 days')).strftime('%m%d%y'))` – etna Oct 02 '17 at 07:39
  • If you happen to search for options, you can as well use Pendulum (https://pendulum.eustace.io): pendulum.now().subtract(days=-1).strftime('%m%d%y') – AFD May 15 '19 at 11:22
175
from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
Nadia Alramli
  • 105,894
  • 35
  • 170
  • 151
22

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
Stef
  • 6,501
  • 4
  • 30
  • 26
11

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 
Iman Mirzadeh
  • 11,510
  • 1
  • 38
  • 42
7

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')
2

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
Community
  • 1
  • 1
Pär Berge
  • 177
  • 11