Reputation: 1011
I've seen some methods using dateutil
module to do this, but is there a way to do this without just using the built in libs?
For example, the current month right now is July. I can do this using the datetime.now()
function.
What would be the easiest way for python to return the previous month?
Upvotes: 6
Views: 14827
Reputation: 921
I was thinking about the shortest solution and I figured out it without using condition.
current_month = datetime.now().month
previous_month = (current_month - 2) % 12 + 1
Upvotes: 1
Reputation: 3145
Generalized function finding the year and month, based on a month delta:
# %% function
def get_year_month(ref_date, month_delta):
year_delta, month_index = divmod(ref_date.month - 1 + month_delta, 12)
year = ref_date.year + year_delta
month = month_index + 1
return year, month
# %% test
some_date = date(2022, 5, 31)
for delta in range(-12, 12):
year, month = get_year_month(some_date, delta)
print(f"{delta=}, {year=}, {month=}")
delta=-12, year=2021, month=5
delta=-11, year=2021, month=6
delta=-10, year=2021, month=7
delta=-9, year=2021, month=8
delta=-8, year=2021, month=9
delta=-7, year=2021, month=10
delta=-6, year=2021, month=11
delta=-5, year=2021, month=12
delta=-4, year=2022, month=1
delta=-3, year=2022, month=2
delta=-2, year=2022, month=3
delta=-1, year=2022, month=4
delta=0, year=2022, month=5
delta=1, year=2022, month=6
delta=2, year=2022, month=7
delta=3, year=2022, month=8
delta=4, year=2022, month=9
delta=5, year=2022, month=10
delta=6, year=2022, month=11
delta=7, year=2022, month=12
delta=8, year=2023, month=1
delta=9, year=2023, month=2
delta=10, year=2023, month=3
delta=11, year=2023, month=4
Upvotes: 0
Reputation: 63
If you just want it as a string then do below process.
import datetime
months =(" Blank", "December", "January", "February", "March", "April",
"May","June", "July","August","September","October","November")
d = datetime.date.today()
print(months[d.month])
Upvotes: 0
Reputation: 61293
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'
>>>
Upvotes: 1
Reputation: 492
If you want a date object:
import datetime
d = datetime.date.today() - datetime.timedelta(days=30)
>>> datetime.date(2015, 6, 29)
Upvotes: -4
Reputation: 172427
It's very easy:
>>> previous_month = datetime.now().month - 1
>>> if previous_month == 0:
... previous_month = 12
Upvotes: 13