Hi my following code provides me with a single digit day(e.g 2015_09_1) even though I'm after 2 digits for yesterdays day:
import time
yesterday = time.strftime("%Y_%m_") + str(int(time.strftime('%d'))-1)
print(yesterday)
Hi my following code provides me with a single digit day(e.g 2015_09_1) even though I'm after 2 digits for yesterdays day:
import time
yesterday = time.strftime("%Y_%m_") + str(int(time.strftime('%d'))-1)
print(yesterday)
OK, first, even if you solved the zero-padding problem, that's not going to work. Today it will say that yesterday was September 0th. On January 1st it will get the year wrong, too.
Just subtract a day (86,400 seconds) from the current time and then format as a string.
yesterday = time.strftime("%Y_%m_%d", time.localtime(time.time()-86400))
If you prefer not to muck around with seconds-based arithmetic, see @taesu's answer using datetime.timedelta
.
from datetime import date, timedelta
d = date.today() - timedelta(days=1)
print d.strftime("%Y_%m_%d")
there's nothing wrong with using time
,
however I personally prefer datetime
, just because it's cleaner.
one reason why I would use this approach is because what if I want to get the day before yesterday, then I would have to 86,400*2
.
with timedelta
, it's simply days=2