给定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