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?
CodePudding user response:
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
CodePudding user response:
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:
- Python date string to date object
- How do I calculate the date six months from the current date using the datetime Python module?
CodePudding user response:
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'