收录日期:2019/10/18 22:07:58 时间:2015-10-01 14:39:51 标签:python,datetime,date

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

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

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

This should do what you want:

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

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

from datetime import datetime, timedelta

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

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'

if you want a one-liner...

from datetime import datetime, timedelta

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