292

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".

the
  • 21,007
  • 11
  • 68
  • 101
y2k
  • 65,388
  • 27
  • 61
  • 86

6 Answers6

505

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Jarret Hardie
  • 95,172
  • 10
  • 132
  • 126
  • 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') – Andrei Drynov May 15 '19 at 11:22
177
from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
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,729
  • 4
  • 34
  • 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
  • 12,710
  • 2
  • 40
  • 44
9

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
  • 196
  • 12