6

I am a beginner programmer in Python and I have no idea how to proceed with the following question. There are a ton of similar questions out there, however there are none having to do with Python code.

I have tried to compare the strings but I am uncertain how to make the comparison. I'm pretty sure I need to take the first two numbers (hours) and divide by 12 if it is greater than 12 ... but that presents problems.

Question:

Time Conversion (24hrs to 12hr)

Write a function that will allow the user to convert the 24 hour time format to the 12 hour format (with 'am','pm' attached). Example: from '1400' to '2:00pm'. All strings passed in as a parameter will have the length of 4 and will only contain numbers.

Examples (tests/calls):

>>> convertTime('0000') '12:00am' >>> convertTime('1337') '1:37pm' >>> convertTime('0429') '4:29am' >>> convertTime('2359') '11:59pm' >>> convertTime('1111') '11:11am' 

Any input or different methods would be awesome!

8
  • 2
    Have a look at strptime and strftime... Commented Nov 25, 2012 at 19:30
  • @JonClements: strptime and strftime are not the right solution for this. Winkleson: What have you tried, and why didn't that work? Commented Nov 26, 2012 at 8:11
  • 1
    @LennartRegebro Any particular reason why? Since Winkleson is a learner, it doesn't hurt to learn the way available using the stdlib, and then alternate methods later. Commented Nov 26, 2012 at 10:27
  • @JonClements: Because it is so way much more complicated and you need to learn loads of things you otherwise don't need to learn, for something that is pretty trivial. datetime.time(), possibly. Besides, this is homework, and then using stdlib is usually not what they teacher wants. Commented Nov 26, 2012 at 10:54
  • @LennartRegebro I was being stupid and runing nested loops to break apart the input... I'm silly.... Thanks for your input. P.s. This isn't homework I am self-teaching myself programming by using tutorials, books and references. I've been out of school for a year and have been working at timmies (Canada F*** yeah) to save up for college :P Commented Nov 26, 2012 at 19:46

3 Answers 3

10

You could use the datetime module, but then you would have to deal with dates as well (you can insert wathever you want there). Probably easier to simply parse it.


Update: As @JonClements pointed out in the comments to the original question, it can be done with a one liner:

from datetime import datetime def convertTime(s): print datetime.strptime(s, '%H%M').strftime('%I:%M%p').lower() 

You can split the input string in the hours and minutes parts in the following way:

hours = input[0:2] minutes = input[2:4] 

And then parse the values to obtain an integer:

hours = int(hours) minutes = int(minutes) 

Or, to do it in a more pythonic way:

hours, minutes = int(input[0:2]), int(input[2:4]) 

Then you have to decide if the time is in the morning (hours between 0 and 11) or in the afternoon (hours between 12 and 23). Also remember to treat the special case for hours==0:

if hours > 12: afternoon = True hours -= 12 else: afternoon = False if hours == 0: # Special case hours = 12 

Now you got everything you need and what's left is to format and print the result:

print '{hours}:{minutes:02d}{postfix}'.format( hours=hours, minutes=minutes, postfix='pm' if afternoon else 'am' ) 

Wrap it up in a function, take some shortcuts, and you're left with the following result:

def convertTime(input): h, m = int(input[0:2]), int(input[2:4]) postfix = 'am' if h > 12: postfix = 'pm' h -= 12 print '{}:{:02d}{}'.format(h or 12, m, postfix) convertTime('0000') convertTime('1337') convertTime('0429') convertTime('2359') convertTime('1111') 

Results in:

12:00am 1:37pm 4:29am 11:59pm 11:11am 
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. That's definitely more than I expected... It really does break everything down in a nice easy to read package :D Also taught me quite a bit like the format function. On the other hand I am a complete idiot... I should have just spliced the integers as you did but instead wasted an hour on complex code that didn't even turn out -_- Anyways thanks for all your help and sorry for the late reply!
2

Some tips int("2300") returns an integer 2300 2300 is PM. time >= 1200 is PM time between 0000 and 1200 is AM.

You could make a function that takes a string, evaluates it as integer, then checks if it is greater or less than the above conditions and returns a print.

5 Comments

@Winkleson: Yes, exactly, just the execution issue. Now you know how to solve the problem, go write the code.
@LennartRegebro Mhm and I was having an issue with it... Because I am silly (look at previous comment). Anyways no need to be a jerk :P I'm not a student in a classroom fishing for free solutions (I was in a computer science class once upon a time... Alice FTW!), I'm just trying to learn Python by myself. I find I learn best with an example to see where I went wrong and then correcting it or by seeing as many potential ways to solve the same problem I am stuck on. For example I cannot copy+paste Garet's answer (morally wrong as well) as I must return the answer. As I barley know format()
@LennartRegebro (cont) I would probably use string replacement ({0] + {1}... etc. Or just return the numbers as a string by appending the minutes and seconds together :P Sorry If I came off as a lazy child (or even adult) but I do love the help and support I have recieved from this website over the past week whether it be positive or negative! Anyways, I'm just procrastinating... Thanks for your help!
@martineau Looking at it through fresh eyes... we'll let;s just say I was thinking about how to return the correct 12h time. I got it now... Thanks though!
@Winkleson: The point of the site is to help you learn, and this is best done if you show the non-working code, and we can tell you what you are doing wrong. As you question stands now it says "Please write my code".
1
import datetime hour = datetime.datetime.now().strftime("%H") minute = datetime.datetime.now().strftime("%M") if int(hour) > 12: hour = int(hour) - 12 amPm = 'PM' else: amPm = 'AM' if int(hour) == 12: amPm = 'PM' if int(hour) == 0: hour = 12 amPm = 'AM' strTime = str(hour) + ":" + minute + " " + amPm print(strTime) 

Take hour and minute from datetime. Convert hour to an int. Check if int(hour) > 12. If so, change from AM to PM. Assign hour with int(hour) - 12. Check if hour is 0 for 12 AM exception. Check if hour is 12 for 12 PM exception. Convert hour back into a string. Print time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.