将 12 小时转换为 24 小时时间 [英] Convert 12 hour into 24 hour times

查看:87
本文介绍了将 12 小时转换为 24 小时时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将时间从 12 小时时间转换为 24 小时时间...

I'm trying to convert times from 12 hour times into 24 hour times...

06:35  ## Morning
11:35  ## Morning (If m2 is anywhere between 10:00 and 12:00 (morning to mid-day) during the times of 10:00 and 13:00 (1pm) then the m2 time is a morning time)
1:35  ## Afternoon
11:35  ## Afternoon

示例代码:

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "%H:%M")
print m2

预期输出:

13:35

实际输出:

1900-01-01 01:35:00

<小时>

我尝试了第二个变体,但还是没有帮助:/


I tried a second variation but again didn't help :/

m2 = "1:35" ## This is in the afternoon.
m2split = m2.split(":")
if len(m2split[0]) == 1:
    m2 = ("""%s%s%s%s""" % ("0", m2split[0], ":", m2split[1]))
    print m2
m2temp = datetime.strptime(m2, "%I:%M")
m2 = m2temp.strftime("%H:%M")

<小时>

我做错了什么,我该如何解决?


What am I doing wrong and how can I fix this?

推荐答案

试试这个 :)

currenttime = datetime.datetime.now().time().strftime("%H:%M")
if currenttime >= "10:00" and currenttime <= "13:00":
    if m2 >= "10:00" and m2 >= "12:00":
        m2 = ("""%s%s""" % (m2, " AM"))
    else:
        m2 = ("""%s%s""" % (m2, " PM"))
else:
    m2 = ("""%s%s""" % (m2, " PM"))
m2 = datetime.datetime.strptime(m2, '%I:%M %p')
m2 = m2.strftime("%H:%M %p")
m2 = m2[:-3]
print m2

输出:

13:35

这篇关于将 12 小时转换为 24 小时时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆