views:

942

answers:

6

Python I need to find "yesterday's" date in this format: MMDDYY

So for instance, today's date would be represented like this: 111009

I can do this for today easy of course but having trouble doing it automatically for "yesterday"

+5  A: 
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(1)
>>> print yesterday.strftime('%m%d%y')
'110909'
Jarret Hardie
+2  A: 

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
Stef
Why do you care more about the date for people in UTC offset 0 than the date in the system's local timezone?
Jeffrey Harris
I copied that from my code, in database usage you often care about UTC. Removed the UTC stuff.
Stef
+2  A: 
import datetime
now = datetime.datetime.now()
now -= datetime.timedelta(days=1)
print now.strftime("%m%d%y")
Ned Batchelder
+1  A: 

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'
unutbu
+11  A: 
from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
Nadia Alramli
+1 for 'days=1'. timedelta(days=1) is clear without having to memorize the docs for timedelta
sdtom
I agree with sdtom... using the kwarg is a nicer touch than my example. +1
Jarret Hardie
Wow! look at how beautiful this is in Java oops I mean Python!
non sequitor
@non sequitor, I don't get the joke.
steveha
steveha, the joke is that his backspace key isn't working.
avakar
A: 

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

from datetime import datetime, timedelta

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