0

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)
Tim
  • 41,901
  • 18
  • 127
  • 145
adama
  • 3
  • 1
  • Why are you going through an int and back to string? If you want two digits, just put the `%d` on the end of the `%Y_%m_` string. – Mark Reed Sep 01 '15 at 20:49
  • @MarkReed then it's not 'yesterday', note the -1 – Tim Sep 01 '15 at 20:50
  • 1
    This is answered at http://stackoverflow.com/questions/441147/how-can-i-subtract-a-day-from-a-python-date –  Sep 01 '15 at 20:56

2 Answers2

2

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.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • thank you! much appreciated! – adama Sep 01 '15 at 21:00
  • 2
    it may produce a wrong date around DST transitions. [There is a difference between "same time a day ago" and "24 hours ago"](http://stackoverflow.com/a/25427822/4279). Note: @taesu's answer works even around DST transitions (except for (rare) cases when the corresponding date does not exist in the local timezone). – jfs Sep 02 '15 at 16:55
2
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

taesu
  • 4,482
  • 4
  • 23
  • 41
  • thank you! much appreciated! – adama Sep 01 '15 at 21:00
  • 1
    [there *is* something wrong with the `time`-based solution](http://stackoverflow.com/questions/32340618/yesterdays-date-and-time-showing-single-digit-day-python?noredirect=1#comment52590622_32340715) – jfs Sep 02 '15 at 16:58
  • thank you. did not know about that. – taesu Sep 02 '15 at 17:05