Formatting "yesterday's" date in python

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

6 Answers

Use datetime.timedelta()

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

This should do what you want:

import datetime yesterday = datetime.datetime.now() - datetime.timedelta(days = 1) print yesterday.strftime("%m%d%y") 
2

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 

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 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like