user11357465
user11357465

Reputation:

How do you find the previous month in YYYY/MM Format

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

Answers (3)

Thierry Lathuille
Thierry Lathuille

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

lmiguelvargasf
lmiguelvargasf

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

geckos
geckos

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

Related Questions