I have a variable like this.
t = 20191201.txt
I want to change this to 20191101
What I am doing here is replacing .txt and then subtracting a month from the date.
How can I do this using Python.
I have a variable like this.
t = 20191201.txt
I want to change this to 20191101
What I am doing here is replacing .txt and then subtracting a month from the date.
How can I do this using Python.
This should work
from datetime import datetime
from dateutil.relativedelta import relativedelta
s = "20191201.txt"
s = s.replace(".txt", "")
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
date -= relativedelta(months=1)
result = date.strftime("%Y%m%d")
print(result)
# 20191101
Almost same answer as yxor:
from datetime import datetime, timedelta
t = '20191201.txt'
d = datetime.strptime(t[:8], "%Y%m%d")
d2 = d - timedelta(365/12)
print d2