ระบุเวลาของพีซีและแปลงเป็นรูปแบบ 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