pythondumb
pythondumb

Reputation: 1207

Python: Command Line Argument is not taking the date properly

I have written a simple function that computes the difference between two given dates.

def dat_diff(d1,d2):
  d_1 = datetime.strptime(d1,'%Y-%m-%d')
  d_2 = datetime.strptime(d2,'%Y-%m-%d')
  if d_1 > d_2:
    diff = d_1 - d_2
  else:
    diff = d_2 - d_1
  return diff.days

Now I want to run this from Windows CMD prompt. For this I am adding following two lines

if __name__=='__main__':
  d1 = sys.argv[0]
  d2 = sys.argv[1]
  dat_diff(d1,d2)

When running from cmd prompt I am getting an error as follows:

ValueError: time data 'C:\\path_to_py_file\\test_cmp_arg.py' does not match format '%Y-%m-%d'

However when from IDE (Spyder in my case) I simply run the function, I get the correct result.

What I am missing here?

Upvotes: 0

Views: 33

Answers (1)

Bhakta Raghavan
Bhakta Raghavan

Reputation: 724

sys.argv[0] is program name

See working code below:

from datetime import datetime
import sys

def dat_diff(d1,d2):
    d_1 = datetime.strptime(d1,'%Y-%m-%d')
    d_2 = datetime.strptime(d2,'%Y-%m-%d')
    if d_1 > d_2:
        diff = d_1 - d_2
    else:
        diff = d_2 - d_1
    return diff.days

if     __name__=='__main__':
  print(sys.argv)
  d1 = sys.argv[1]
  d2 = sys.argv[2]
  print("Diff is {} days".format(dat_diff(d1,d2)))

And on running it:

# python d.py  2020-12-31 2020-01-01
['d.py', '2020-12-31', '2020-01-01']
Diff is 365 days

Upvotes: 1

Related Questions