Home » Python » Formatting “yesterday's” date in python

Formatting “yesterday's” date in python

Posted by: admin November 1, 2017 Leave a comment

Questions:

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

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

Questions:
Answers:
from datetime import datetime, timedelta

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

Questions:
Answers:

This should do what you want:

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

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

Questions:
Answers:

This should do the trick. Stolen from the python mailing list.

from datetime import datetime, timedelta

today = datetime.today()
yesterday = today - timedelta(1)

Questions:
Answers:

You can find all the string format codes here: http://au2.php.net/strftime

In [1]: import datetime

In [2]: today=datetime.date.today()

In [3]: yesterday=today-datetime.timedelta(1)

In [4]: yesterday.strftime('%m%d%y')
Out[4]: '110909'

Questions:
Answers:

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

Questions:
Answers:

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 

Questions:
Answers:

if you want a one-liner…

from datetime import datetime, timedelta

yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')