Reputation:
It's quite simple. I like to find the previous month for the current time, but in YYYY/MM Date Format. Ideally using Datetime.
Upvotes: 0
Views: 2398
Reputation: 24291
Using only the datetime module from the standard library, we can get the month and year from 15 days before the start of our month:
from datetime import date, timedelta
def previous_month():
format = '%Y/%m'
d = date.today().replace(day=1) # first day of the month
return date.strftime(d-timedelta(days=15), format) # 15 days earlier is in the previous month
previous_month()
# '2019/08
Upvotes: 0
Reputation: 70003
Use months
with relativedelta
:
>>> from dateutil.relativedelta import relativedelta
>>> (datetime.now() - relativedelta(months=1)).strftime('%Y/%m')
'2019/08'
This covers the case you said:
>> (datetime.strptime('01/03/2019', '%d/%m/%Y') - relativedelta(months=1)).strftime('%Y/%m')
'2019/02'
Upvotes: 3
Reputation: 6299
from datetime import datetime, timedelta
(datetime.now() - timedelta(days=30)).strftime('%Y/%m')
This may suffice depending on your needs, a more sophisticated approach may use libraries from pip, like dateutil
from dateutil.relativedelta import relativedelta
(datetime.now() - relativedelta(months=1)).strftime('%Y/%m')
Regards
Upvotes: 1