0

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.

  • 3
    Does this answer your question? [How to convert integer into date object python?](https://stackoverflow.com/questions/9750330/how-to-convert-integer-into-date-object-python) – Loïc Nov 22 '19 at 12:40

2 Answers2

1

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
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
-1

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
Tobias
  • 12
  • 4