Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

python - 0-23 hour military clock to standard time (hh:mm)

How would I go about this process? Let's say that someone types in "3:5", and I should be able to get the output "3:05 AM". Or if someone types in "00:00", I should get "12:00 AM". I realize the plethora of ways to go about this if the time format was simply input as "hhmm", but the input can range from "h:m", "hh:m", "hh:m", and "hh:mm". So it's very situational.

def timeConvert():
    miliTime = int(input("Enter a time in hh:mm (military) format: "))
    miliTime.split(":")
    if len(miliTime) == 3:
        hours = miliTime[0]
        minutes = miliTime[2]
        if hours < 0:
            print("Hours can't be less than 0.")
    elif len(miliTime) == 4:
        if miliTime[0:2] >= 10:
            hours = militime[0:2]
            minutes = militime[3]
            if minutes < 0:
                print("Minutes can't be less than 0.")
            if minutes < 10:
                minutes = 0 + minutes
        else:
            hours = miliTime[0]
            minutes = militime[2:]
            if minutes >= 60:
                print("Too big of a number for minutes.")
    else:
        hours = miliTime[0:2]
        minutes = miliTime[3:]
    setting = AM
    if hours > 12:
        setting = PM
        hours -= 12
    print(hours + ":" + minutes + setting)

timeConvert()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the datetime module's strptime() to read the string as a datetime object and then convert it back to string using strftime() , example -

>>> datetime.datetime.strptime('3:5','%H:%M').strftime('%I:%M %p')
'03:05 AM'
>>> datetime.datetime.strptime('18:30','%H:%M').strftime('%I:%M %p')
'06:30 PM'
>>> datetime.datetime.strptime('00:00','%H:%M').strftime('%I:%M %p')
'12:00 AM'

The formats explained -

%H - Hour (24-hour fomrat)

%M - Minute

%I - Hour (12-hour format)

%p - AM or PM


Function would look like -

def timeConvert():
    import datetime
    ds = input("Enter a time in hh:mm (military) format: ")
    newds = datetime.datetime.strptime(ds, ,'%H:%M').strftime('%I:%M %p')
    print(newds)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...