Python程序将时间从12小时转换为24小时格式
给定PC的时间,它将转换为24小时格式。在这里,我们将应用字符串切片。
在这里,如果时间是PM,则按规则,然后加上小时部分的12;如果时间是AM,则不添加。
示例
Input: 12:20:20 PM Output: 24:20:20
算法
Step 1: Input current datetime. Step 2: Extract only time from datetime format. Step 3: Using string slicing check last two words PM or AM. Step 4: if last two word is PM then add 12 and if word are AM then don't add it.
范例程式码
import datetime
def timeconvert(str1):
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]
elif str1[-2:] == "AM":
return str1[:-2]
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]
else:
return str(int(str1[:2]) + 12) + str1[2:8]
dt=datetime.datetime.now()
print("Conversion Of Time ::",timeconvert(dt.strftime("%H:%M:%S")))输出结果
Conversion Of Time :: 24:04:53
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短