Search in the previous month

I've seen some methods using a module dateutil

to do this, but is there a way to do this without using the built-in libraries?

For example, the current month is now July. I can do this using a function datetime.now()

.

What would be the easiest way to get python back to the previous month?

+3


source to share


3 answers


It's very simple:



>>> previous_month = datetime.now().month - 1
>>> if previous_month == 0:
...     previous_month = 12

      

+8


source


You can use the calendar

module



>>> from calendar import  month_name, month_abbr
>>> d = datetime.now()
>>> month_name[d.month - 1] or month_name[-1]
'June'
>>> month_abbr[d.month - 1] or month_abbr[-1]
'Jun'
>>> 

      

+1


source


If you want a date object:

import datetime
d = datetime.date.today() - datetime.timedelta(days=30)
>>> datetime.date(2015, 6, 29)

      

-2


source







All Articles