python24小时12小时转换_Python上24小时时间转换为12小时制(ProblemSetQuestion)
你可以使用datetime模塊,但是你也必須處理日期(你可以在那里插入你想要的觀察者).可能更容易簡(jiǎn)單地解析它.
更新:正如@JonClements在對(duì)原始問(wèn)題的評(píng)論中指出的那樣,它可以通過(guò)一個(gè)班輪完成:
from datetime import datetime
def convertTime(s):
print datetime.strptime(s, '%H%M').strftime('%I:%M%p').lower()
您可以按以下方式拆分小時(shí)和分鐘部分中的輸入字符串:
hours = input[0:2]
minutes = input[2:4]
然后解析值以獲取整數(shù):
hours = int(hours)
minutes = int(minutes)
或者,以更加pythonic的方式做到:
hours, minutes = int(input[0:2]), int(input[2:4])
然后你必須決定時(shí)間是早上(0到11之間)還是下午(12到23之間).還要記住將特殊情況視為小時(shí)== 0:
if hours > 12:
afternoon = True
hours -= 12
else:
afternoon = False
if hours == 0:
# Special case
hours = 12
現(xiàn)在你得到了你需要的一切,剩下的就是格式化和打印結(jié)果:
print '{hours}:{minutes:02d}{postfix}'.format(
hours=hours,
minutes=minutes,
postfix='pm' if afternoon else 'am'
)
將它包裝在一個(gè)函數(shù)中,使用一些快捷方式,并留下以下結(jié)果:
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')
結(jié)果是:
12:00am
1:37pm
4:29am
11:59pm
11:11am
總結(jié)
以上是生活随笔為你收集整理的python24小时12小时转换_Python上24小时时间转换为12小时制(ProblemSetQuestion)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: 算法设计学习---递归
- 下一篇: 人体体表红外测温仪方案PCBA设计
