Fabricio Carboni Fabricio Carboni - 3 months ago 10
Python Question

Python: define a string variable pattern

I'm new to python.

I have a program that reads from

str(sys.argv[1])
:

myprogram.py "some date" # I'd like this in YYYYMMDD format. I.e:
myprogram.py 20160806


if __name__ == '__main__':
if str(sys.argv[1]):
CTRL = str(sys.argv[1])
print "some stuff"
sys.exit()


I need "some date" in YYYYMMDD format. How could it be possible? I've googled variable mask, variable pattern and nothing came out.

Thanks for your help and patience.




UPDATE:

Fortunately all answers helped me!

As the CTRL variable gaves me 2016-08-17 00:00:00 format, I had to convert it to 20160817. Here is the code that worked for me:

if str(sys.argv[1]):
CTRL_args = str(sys.argv[1])

try:
CTRL = str(datetime.datetime.strptime(CTRL_args, "%Y%m%d")).strip().split(" ")[0].replace("-","").replace(" ","").replace(":","")
# do some stuff
except ValueError:
print('Wrong format!')
sys.exit()

Answer

I'm not allowed to comment so I have to write this as an answer... sorry!

Anyways, if I understand what you said right, you want to pass an argument in a YYYYMMDD format.

There is nothing stopping you from doing this with your script.

You can run: python yourscript.py YYYYMMDD and a string "YYYYMMDD" will be stored in the CTRL variable.

Let me know if you meant something else with your question and I'll try to help :)


UPDATE:

The following routine does the checks you are asking for:

Let me know if you need me to explain any of it!

import sys
from datetime import datetime

if __name__ == '__main__':
    try:
        CTRL = str(sys.argv[1])
    except IndexError:
        print "You have not specified a date!"
        sys.exit()

    try:
        parced_CTRL = datetime.strptime(CTRL, "%Y%m%d")
    except ValueError:
        print "Please input date in the YYYYMMDD format!"
        sys.exit()

    print "Date is in the correct format!"
    print "Data = {}".format(parced_CTRL)
Comments