0

Is it possible to combine sys module and time module in python? I want to write a program that check if the sys argument that the user has put in is in the right time format e.g. "%H:%M"

begginer
  • 1
  • 2
  • Does this answer your question? [How to pass timestamp as a command line argument in python?](https://stackoverflow.com/questions/51343230/how-to-pass-timestamp-as-a-command-line-argument-in-python) – wjandrea Mar 26 '21 at 22:34
  • Semi-duplicates: [How to validate a specific Date and Time format using Python](https://stackoverflow.com/q/18539266/4518341) and [What's the best way to parse command line arguments?](https://stackoverflow.com/q/20063/4518341) – wjandrea Mar 26 '21 at 22:37

1 Answers1

0

Read about argparse, it's a nice library for parsing arguments in python, You can find it in here.

One approach for handling that question would be to use type argument while adding it to parser, the type can be any function that will validate your format. e.g -

def validate(arg):
    try:
        return datetime.strptime(arg, "%H:%M")
    except ValueError:
        msg = f"Invalid date fmt {arg}"
        raise argparse.ArgumentTypeError(msg)

Now just assign above function as type while adding argument by parser.add_argument.

Hook
  • 355
  • 1
  • 7