0

I have to a run a python script in command line and pass the date as argument and below is my command to run the date

parser = argparse.ArgumentParser()
parser.add_argument('date')
tdate= parser.parse_args().date

i would like to change this to check if it is sunday or saturday. If it is saturday, tdate should be tdate-1 and if it is sunday , it should be tdate-2.

I tried to get weekno in python and if it is 5, i am considering this as saturday and if it is 6 then it is sunday.

#this code is in python getting today() weekday()
weekno = datetime.datetime.today().weekday()
if weekno==5:
    tdate= parser.parse_args().date-1
elif weekno==6:
    tdate= parser.parse_args().date-2
else:
    tdate= parser.parse_args().date

I am missing something in this code. Can anyone please help me ?

Gerhard
  • 22,678
  • 7
  • 27
  • 43
unicorn
  • 496
  • 6
  • 20

1 Answers1

0

If I'm understanding correctly, you want it so that if the current day is either Saturday or Sunday, then the entered date that is passed as a command line argument should be date - 1 day or date - 2 days.

So, if today's date is passed (11/23/2022) on Monday-Friday it'll return the date as is but if the same date is passed on Saturday, it'll return 11/22/2022.

To do the operation of subtracting days from the current day you'll need to use time delta.

This is my solution based of my assumptions of what you are asking

import argparse
from datetime import datetime, timedelta

parser = argparse.ArgumentParser()
parser.add_argument('date')
passed_in_date = parser.parse_args().date

tdate = datetime.strptime(passed_in_date, "%m/%d/%Y")


weekno = datetime.today().weekday()
print(f"weekno of today is: {weekno}")
if weekno==5:
    tdate = tdate - timedelta(days=1)
elif weekno==6:
    tdate = tdate - timedelta(days=2)


print(tdate.date())

OutPut

#running on a Wednesday (for example) date returns same as passed
python .\date.py 11/26/2022
weekno of today is: 2
2022-11-26

#example for testing if running on a sunday
python .\date.py 11/23/2022
weekno of today is: 6
2022-11-21

If you wanted to see the date change just manually set weekno to 5 or 6 for testing.

kconsiglio
  • 401
  • 1
  • 8