Faced with a ValueError: month out of range error. Please tell me the reason and how to correct the error. Briefly about the meaning of the script: enter the month, day, year, we get the output data object in a specific format. Then I will finish writing the script to display only the day of the week, without the data entered.

%%writefile day_finder.py import time, datetime import argparse parser = argparse.ArgumentParser() parser.add_argument("month", type = int, help = "Month as a number (1, 12)") parser.add_argument("day", type = int, help = "Day as a number (1, 31) depending on the month") parser.add_argument("year", type = int, help = "Year as a 4 digits number (2018)") parser.add_argument("-c", "--complete", action = 'store_true', help = "Show complete formatted date") args = parser.parse_args() d = () d = (args.month, args.day, args.year, 0, 0 , 0 , 0, 0, 0) date_v = time.strftime("%m,%d,%Y", d) print (date_v) 

Running the script:

 %%bash python3 day_finder.py 12 31 2017 
  • one
    d = (args.year, args.month, args.day, 0, 0 , 0 , 0, 0, 0) ? - MaxU 2:01 pm
  • when I ask only three arguments, it says that it’s not enough and you need at least 9. I threw in zeros for all hours, seconds, etc. and the error disappeared. Although most likely this is also some kind of crooked solution. - Anton Zubochenko
  • 3
    Use: datetime.date(args.year, args.month, args.day).strftime("%m,%d,%Y") - MaxU

1 answer 1

To determine the date, use datetime (I understand it more suited to your task), for this you need 3 input parameters in the format int - year, month and day, the order is strict:

 import datetime d = datetime.date(args.year, args.month, args.day) print type(datetime.date(2018, 9, 16)) # <type 'datetime.date'> 

You tried to form a tuple and use the time module. You have a tuple of such a structure:

 d = (9, 16, 2018, 0, 0, 0, 0, 0, 0) 

When executing date_v = time.strftime("%m,%d,%Y", (9, 16, 2018, 0, 0, 0, 0, 0, 0)) get the error that there is no 16th month. In some cases, the team would work (12 - it will be for example 2012), but the result would be incorrect:

 time.strftime("%m,%d,%Y", (12, 9, 9, 0, 0, 0, 0, 0, 0)) # '09,09,2012' 

Reign strict indication of the year, month, day and beyond. Those. you can specify in formatting as you like, but you do not need to adjust the tuple - it is strictly there.