0

I am extracting the date from a filename and storing it in a string variable. Suppose the filename is CRM_DATA_PUBLIC_20201120_052035.txt, I have extracted the date as 20201120. Now I want to get the previous month's date from this, like 20201020 or just 202010. I tried using date functions but it is giving error for me.

Could you please help me out here ?

Thanks in anticipation.

Tech Fukrey
  • 39
  • 2
  • 8

2 Answers2

1

Try this: (changes based on a comment)

import datetime
from dateutil.relativedelta import relativedelta

filename = 'CRM_DATA_PUBLIC_20201120_052035.txt'
date = filename.split('_')[3]

#If you want the output to include the day of month as well
date = datetime.datetime.strptime(date, '%Y%m%d')

#If you want only the month
date = datetime.datetime.strptime(date, '%Y%m')

date = date - relativedelta(months=1)
date = str(date.date()).replace('-','')

print(date)

Output:

20201020
idar
  • 614
  • 6
  • 13
  • 1
    For formatting the date string you could also use `date = datetime.datetime.strftime(date, "%Y%m%d")` and specify the format `"%Y%m%d"` (with day) or `%Y%m` (without day). – rftr Dec 10 '20 at 09:44
0

You can find your answer here https://stackoverflow.com/a/9725093/10334833 What I get from your question is already answered here but if you are still confused let me know I can help you :)

ashhad ullah
  • 116
  • 4