Python: define a string variable pattern
Question: 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: you need function **datetime.strptime** with mask **%Y%m%d**

    
    
    import sys
    from datetime import datetime
    
    if __name__ == '__main__':
        if str(sys.argv[1]):
            CTRL = str(sys.argv[1])
            try:
                print datetime.strptime(CTRL, "%Y%m%d")
            except ValueError:
                print 'Wrong format'
            sys.exit()
    

Output:

    
    
    $ python example.py 20160817
    2016-08-17 00:00:00
    

