python24小时12小时转换_python将时间从12小时转换为24小时格式
給出12小時AM / PM格式的時間,將其轉換為軍事(24小時)時間。
注意:午夜是12小時制的凌晨12:00:00和24小時制的00:00:00。中午是12小時制的12:00:00 PM和24小時制的12:00:00。
例子 : :Input : 11:21:30 PM
Output : 23:21:30
Input : 12:12:20 AM
Output : 00:12:20
方法:時間格式是否為12小時,可以通過列表切片找到。檢查最后兩個元素是否為PM,然后只需添加12個元素。如果是AM,則不要添加。從更新的時間刪除AM / PM。
# Python program to convert time
# from 12 hour to 24 hour format
# Function to convert the date format
def convert24(str1):
# Checking if last two elements of time
# is AM and first two elements are 12
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]
# remove the AM
elif str1[-2:] == "AM":
return str1[:-2]
# Checking if last two elements of time
# is PM and first two elements are 12
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]
else:
# add 12 to hours and remove PM
return str(int(str1[:2]) + 12) + str1[2:8]
# Driver Code
print(convert24("08:05:45 PM"))
輸出: :20:05:45
總結
以上是生活随笔為你收集整理的python24小时12小时转换_python将时间从12小时转换为24小时格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: uniapp 离线打包 配置googl
- 下一篇: websocket python爬虫_p