Find previous calendar day in python

35,450

Solution 1

Here you go:

>>> print datetime.date.today()-datetime.timedelta(1)
>>> 2010-06-19

Solution 2

Say you start with a string '2010_05_1'. Then the similar string for the previous day is:

>>> import datetime
>>> s = '2010_05_1'
>>> theday = datetime.date(*map(int, s.split('_')))
>>> prevday = theday - datetime.timedelta(days=1)
>>> prevday.strftime('%Y_%m_%d')
'2010_04_30'
>>> 

Of course you'll encapsulate all of this into one handy function!

Solution 3

You can use the datetime module.

import datetime
print (datetime.date(year, month, day) - datetime.timedelta(1)).isoformat()
Share:
35,450
Xavier
Author by

Xavier

Updated on June 21, 2020

Comments

  • Xavier
    Xavier almost 4 years

    Possible Duplicate:
    How can I subtract a day from a python date?

    I have a set of files that I'm saving by date, year_month_day.txt format. I need to open the previous day's text file for some processing. How do I find the previous day's date in python?