Formatting "yesterday's" date in python

PythonDatetimeDate

Python Problem Overview


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

Python Solutions


Solution 1 - Python

Use datetime.timedelta()

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

Solution 2 - Python

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')

Solution 3 - Python

This should do what you want:

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

Solution 4 - Python

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 

Solution 5 - Python

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

Solution 6 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiony2kView Question on Stackoverflow
Solution 1 - PythonJarret HardieView Answer on Stackoverflow
Solution 2 - PythonNadia AlramliView Answer on Stackoverflow
Solution 3 - PythonStefView Answer on Stackoverflow
Solution 4 - PythonIman MirzadehView Answer on Stackoverflow
Solution 5 - PythonArvid BäärnhielmView Answer on Stackoverflow
Solution 6 - PythonPär BergeView Answer on Stackoverflow