Search code examples
pythontimestrftime

yesterdays date and time showing single digit day - python


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)

Solution

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