Fabricio Carboni
Fabricio Carboni

Reputation: 15

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()

Upvotes: 1

Views: 181

Answers (2)

tpvasconcelos
tpvasconcelos

Reputation: 717

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 your CTRL variable.


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)

UPDATE:

If you want to parse dates in the YYYY-MM-DD format you need to do this instead:

parced_CTRL = datetime.strptime(CTRL, "%Y-%m-%d")

I think it is self explanatory... ;)

Upvotes: 0

g1zmo
g1zmo

Reputation: 487

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

Upvotes: 2

Related Questions