Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Military Time Converter Assignment

Here's the assignment 1665074835138.png
Python:
def military_time():
    mil_time = int(input("Please enter military time: "))
    for i in range(mil_time):  # I'm "subscripting" so it isn't allowing me to check through the index but that is my goal
        if(int(mil_time[0:1]) % 12): # new to modula but it seems simple to implement for this assignment
            print(mil_time)





    #print(str(civilian_hours) + ":" + str(minutes), civilian_ampm) example code provided as a hint

if __name__ == '__main__':
    military_time()

running into so many errors with every different attempt, a push to the right direction would be appreciated a lot.
 
Here's the assignment View attachment 1673
Python:
def military_time():
    mil_time = int(input("Please enter military time: "))
    for i in range(mil_time):  # I'm "subscripting" so it isn't allowing me to check through the index but that is my goal
        if(int(mil_time[0:1]) % 12): # new to modula but it seems simple to implement for this assignment
            print(mil_time)





    #print(str(civilian_hours) + ":" + str(minutes), civilian_ampm) example code provided as a hint

if __name__ == '__main__':
    military_time()

running into so many errors with every different attempt, a push to the right direction would be appreciated a lot.
Hey there,
Best way to approach this would be to start listing off errors :)
 
Unless it's a required, I do not understand why you are using a loop.

Steps to take:
  1. Get hrs, get minutes, and determine if it's am or pm (hint - hours and minutes can be gotten using string slice)
  2. Display 12 if it's am otherwise display the correct hour
  3. Display finished time example: 12:05 AM
  4. On a side note: minutes will need formating so you will have an output like 12:05 instead of 12:5
 
Last edited:
Also, there might be an easier way. Let's see, as far as splitting up the time into hh:mm, it seems you are always entering 4 digits as hhmm. So that being the case, you could just split the input into the hrString and minString.

convert hrString to int and compare for ampm
Code:
if hrConvertedInt >= 0 && hrConvertedInt <= 11:
    dayIndicator = "AM"
else:
    dayIndicator = "PM"

So when you create your output string you can do something like this
Code:
if hrConvertedInt equals 0:
    hrString equals "12"
else:
    hrString equals hrConvertedInt % 12

if minConvertedInt >= 0 and minConvertedInt <= 9:
    minString = "0" + minConvertedInt

toPrintString = hrString + ":" + minString + dayIndicator
 
I took the approach with a one liner:
Python:
hrs = 12 if hrs == 0 else hrs
Using try, except block for error checking
Also a length check of at least four digits for input
Used one if else for converting plus the one liner
I kept the input as a string until needed as an int then converted


To add to Antero360's example for dayIndicator could also be written using a chain if
Python:
dayIndicator = 'AM' if 0 <= n < 12 else 'PM'
 
Last edited:
Got it working, forgot I could only slice when its a string so that was a huge help, still learning how the indexes work but nonetheless
Python:
def military_time():
    mil_time = (input("Please enter military time: "))
    
    if(int(mil_time) >= 1200):
        civilian_ampm = "pm"
        if(int(mil_time) == 1200):
            mil_time = "1200"
            civilian_hours = mil_time[0:2]
            minutes = mil_time[2: ]
        elif(int(mil_time) == 2400):
            mil_time = "1200"
            civilian_hours = mil_time[0:2]
            minutes = mil_time[2:]
            civilian_ampm = "am"
        else:
            civilian_hours = mil_time[0:2]
            civilian_hours = int(civilian_hours) % 12

            minutes = mil_time[2: ]
    else:
        civilian_ampm = "am"
        civilian_hours = mil_time[1]
        minutes = mil_time[2: ]

    print(str(civilian_hours) + ":" + str(minutes), civilian_ampm)

if __name__ == '__main__':
    military_time()
 
This should work:

Python:
military_time = input("Enter the military time: ")

military_hour, minute = military_time[:2], military_time[2:]

if military_hour == "00":
  hour = "12"
  state = "AM"
elif int(military_hour) > 12:
  hour = int(military_hour) - 12
  state = "PM"
else:
  hour = military_hour
  state = "AM"

print(f"The time is {hour}:{minute} {state}")
 
My go at it
Python:
# Get user input
mil_time = input('>> ')

# Checking if input is at least four characters
if len(mil_time) < 4:
    print('Four digits are required to convert time.')
    exit()

# Try/except block to check if only whole numbers are entered
try:
    # Getting hours and minutes from input using string slice
    hours, minutes = int(mil_time[:2]), mil_time[2:]
    # Setting and checking hour for day indication
    day_indicator = 'AM' if 0 <= hours < 12 else 'PM'
except ValueError:
    print('Only whole numbers are allowed')

# If hour is greater than 12 get the modulous hour else use hour
hours = hours % 12 if hours > 12 else (12 if hours == 0 else hours)

# If minutes entered is greater than 59 set minutes to 59
minutes = minutes if int(minutes) < 60 else 59

# Print the time string
print(f'{hours}:{minutes} {day_indicator}')
 
Last edited:
So i fixed it but not as cleanly as you all have done
Python:
def military_time():
    mil_time = (input("Please enter military time: "))
    civilian_hours = int(mil_time[ :2])
    minutes = int(mil_time[2: ])
    if(civilian_hours <= 11) and (civilian_hours != 24) or (civilian_hours == 00):
        civilian_ampm = "AM"
    else:
        civilian_ampm = "PM"
    if(civilian_hours < 10) and (civilian_hours != 00):
        civilian_hours = (mil_time[1])
        minutes = (mil_time[ 2: ])
    elif(civilian_hours == 00):
        civilian_hours = 12
        minutes = (mil_time[2:])
    elif(civilian_hours == 24):
        civilian_hours = 12
        minutes = (mil_time[2:])
    elif(civilian_hours > 12):
        civilian_hours = civilian_hours % 12
        minutes = (mil_time[2:])



    print(str(civilian_hours) + ":" + str(minutes), civilian_ampm)

if __name__ == '__main__':
    military_time()
 
Took it a step further added more error checking, added a while loop, and added a little color. I do not know if it will work on all os. I'm using ubuntu and it works in the terminal and vs studio.

Python:
from os import system, name
def clear():
    system('cls' if name == 'nt' else 'clear')
colors = {
    'default': '\033[1;39m',
    'orange': '\033[38:5:208m',
    'red': '\033[38:5:196m',
    'gold': '\033[38:5:220m',
    'light green': '\033[38:5:120m'
}
clear()
while True:
    # Get user input
    print(f'{colors["orange"]}Enter q to exit{colors["default"]}')
    mil_time = input('Enter a military time\n>> ')
    if mil_time == 'q':
        clear()
        print(f'{colors["orange"]}Thanks for using time convert{colors["default"]}')
        break
    if mil_time.isalpha():
        clear()
        print(f'{colors["red"]}You can only enter whole numbers{colors["default"]}')
        continue
    # Checking if input is at least four characters
    if len(mil_time) < 4:
        clear()
        print(f'{colors["red"]}Four digits are required to convert time.{colors["default"]}')
        continue
    if int(mil_time[:1]) > 2:
        clear()
        print(f'{colors["red"]}The first digit of militay time can not exceed 2.{colors["default"]}')
        continue
    if int(mil_time[1:2]) > 3:
        clear()
        print(f'{colors["red"]}The second digit of military time can not exceed 3{colors["default"]}')
        continue
    # Try/except block to check if only whole numbers are entered
    try:
        # Getting hours and minutes from input using string slice
        hours, minutes = int(mil_time[:2]), mil_time[2:]
        # Setting and checking hour for day indication
        day_indicator = 'AM' if 0 <= hours < 12 else 'PM'
    except ValueError:
        clear()
        print(f'{colors["red"]}Only whole numbers are allowed{colors["default"]}')
        continue
    # If hour is greater than 12 get the modulous hour else use hour
    hours = hours - 12 if hours > 12 else (12 if hours == 0 else hours)
    # If minutes entered is greater than 59 set minutes to 00
    minutes = minutes if int(minutes) < 60 else 59
    # Print the time string
    clear()
    print(f'{colors["light green"]}Civilian Time:{colors["gold"]} {hours}:{minutes} {day_indicator}{colors["default"]}\n')
 
Took it a step further added more error checking, added a while loop, and added a little color. I do not know if it will work on all os. I'm using ubuntu and it works in the terminal and vs studio.

Python:
from os import system, name
def clear():
    system('cls' if name == 'nt' else 'clear')
colors = {
    'default': '\033[1;39m',
    'orange': '\033[38:5:208m',
    'red': '\033[38:5:196m',
    'gold': '\033[38:5:220m',
    'light green': '\033[38:5:120m'
}
clear()
while True:
    # Get user input
    print(f'{colors["orange"]}Enter q to exit{colors["default"]}')
    mil_time = input('Enter a military time\n>> ')
    if mil_time == 'q':
        clear()
        print(f'{colors["orange"]}Thanks for using time convert{colors["default"]}')
        break
    if mil_time.isalpha():
        clear()
        print(f'{colors["red"]}You can only enter whole numbers{colors["default"]}')
        continue
    # Checking if input is at least four characters
    if len(mil_time) < 4:
        clear()
        print(f'{colors["red"]}Four digits are required to convert time.{colors["default"]}')
        continue
    if int(mil_time[:1]) > 2:
        clear()
        print(f'{colors["red"]}The first digit of militay time can not exceed 2.{colors["default"]}')
        continue
    if int(mil_time[1:2]) > 3:
        clear()
        print(f'{colors["red"]}The second digit of military time can not exceed 3{colors["default"]}')
        continue
    # Try/except block to check if only whole numbers are entered
    try:
        # Getting hours and minutes from input using string slice
        hours, minutes = int(mil_time[:2]), mil_time[2:]
        # Setting and checking hour for day indication
        day_indicator = 'AM' if 0 <= hours < 12 else 'PM'
    except ValueError:
        clear()
        print(f'{colors["red"]}Only whole numbers are allowed{colors["default"]}')
        continue
    # If hour is greater than 12 get the modulous hour else use hour
    hours = hours - 12 if hours > 12 else (12 if hours == 0 else hours)
    # If minutes entered is greater than 59 set minutes to 00
    minutes = minutes if int(minutes) < 60 else 59
    # Print the time string
    clear()
    print(f'{colors["light green"]}Civilian Time:{colors["gold"]} {hours}:{minutes} {day_indicator}{colors["default"]}\n')
I'm not sure if those will work on Windows, here's a file of all the ANSI Escape Sequences I have that are cross platform. Please note that the old windows terminal doesn't support these (the new one does though).

 
Updated code

Python:
from os import system, name
def clear():
    system('cls' if name == 'nt' else 'clear')
colors = {
    'default': '\u001b[0m',
    'cyan': '\u001b[36m',
    'red': '\u001b[31m',
    'yellow': '\u001b[33m',
    'green': '\u001b[32m'
}
clear()
while True:
    # Get user input
    print(f'{colors["cyan"]}Enter q to exit{colors["default"]}')
    mil_time = input('Enter a military time\n>> ')
    if mil_time.lower() in ['q','quit', 'exit']:
        clear()
        print(f'{colors["yellow"]}Thanks for using time convert{colors["default"]}')
        break
    if mil_time.isalpha():
        clear()
        print(f'{colors["red"]}You can only enter whole numbers{colors["default"]}')
        continue
    # Checking if input is at least four characters
    if len(mil_time) < 4:
        clear()
        print(f'{colors["red"]}Four digits are required to convert time.{colors["default"]}')
        continue
    if len(mil_time) > 4:
        mil_time = mil_time[:4]
    if int(mil_time[:2]) > 23:
        clear()
        print(f'{colors["red"]}Military hours can\'t exceed 23{colors["default"]}')
        continue
    # Try/except block to check if only whole numbers are entered
    try:
        # Getting hours and minutes from input using string slice
        hours, minutes = int(mil_time[:2]), mil_time[2:]
        
        # Setting and checking hour for day indication
        day_indicator = 'AM' if 0 <= hours < 12 else 'PM'
    except ValueError:
        clear()
        print(f'{colors["red"]}Only whole numbers are allowed{colors["default"]}')
        continue
    # If hour is greater than 12 get the modulous hour else use hour
    hours = hours - 12 if hours > 12 else (12 if hours == 0 else hours)
    # If minutes entered is greater than 59 set minutes to 00
    minutes = minutes if int(minutes) < 60 else 59
    # Print the time string
    clear()
    print(f'{colors["green"]}Civilian Time:{colors["yellow"]} {hours}:{minutes} {day_indicator}{colors["default"]}\n')
 

Attachments

  • Screenshot from 2022-10-08 04-06-30.png
    Screenshot from 2022-10-08 04-06-30.png
    22.2 KB · Views: 4
Last edited:

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom