热线电话:13121318867

登录
2019-04-10 阅读量: 1134
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
17.0792
4
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子