Reputation: 39
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.
Upvotes: 0
Views: 170
Reputation: 610
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
Upvotes: 1
Reputation: 116
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 :)
Upvotes: 0