0

I have a date object like

Date = '202011'

This is yyyymm format.

I want to get the same month but n years prior. For example if n = 2, then I should get '201811'

Is there any function available to achieve this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Bogaso
  • 2,838
  • 3
  • 24
  • 54

3 Answers3

2

Just parse it into a Python datetime object and use its replace() method.

from datetime import datetime

years_ago = 2
date = datetime.strptime('202011','%Y%m')
date = date.replace(year=date.year-years_ago)

# This is the modified date object
print(date)

# Formatted back in your format
print(date.strftime('%Y%m'))

This solution does not require any external dependency

Newbie
  • 4,462
  • 11
  • 23
2

You can use the datetime module and dateutil library for this:

import datetime
from dateutil.relativedelta import relativedelta

fmt = '%Y%m'
date_string = '202011'
n = 2

# Parse `date_string` into a date object.
date = datetime.datetime.strptime(date_string, fmt).date()
# 2020-11-01

# Subtract `n` years.
new_date = date + relativedelta(years=-n)

# Output in the same format.
print(new_date.strftime(fmt))  # -> 201811

Related questions:

wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

Here's a similar solution to the others, but only using the standard library, and as a function.

def subtract_years(date_string: str, diff: int) -> str:
    dt = datetime.strptime(date_string, "%Y%m")
    new_dt = dt.replace(year=dt.year - diff)
    return new_dt.strftime("%Y%m")

# ❯ subtract_years("202011", 2)
# '201811'
blueteeth
  • 3,330
  • 1
  • 13
  • 23
  • Thanks. Just curious what is the use and meaning of `-> str` part in your code? – Bogaso Sep 06 '22 at 23:21
  • That's for [type hinting](https://docs.python.org/3/library/typing.html). So it's declaring that `date_string` is a string, `diff` is an integer, and when you call this function, it returns a string. – blueteeth Sep 07 '22 at 07:24