将12小时转换为24小时

时间:2013-10-07 15:51:34

标签: python python-2.7 time

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

自动示例时间:

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

我尝试了第二种变化但又没有帮助:/

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")

我做错了什么,如何解决这个问题?

12 个答案:

答案 0 :(得分:19)

你需要指明你的意思是PM而不是AM。

>>> from datetime import *
>>> m2 = '1:35 PM'
>>> m2 = datetime.strptime(m2, '%I:%M %p')
>>> print(m2)
1900-01-01 13:35:00

答案 1 :(得分:13)

这种方法使用strptime和strftime格式指令按照https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior,%H是24小时制,%I是12小时制,当使用12小时制时,%p符合条件是否为AM或PM。

    >>> from datetime import datetime
    >>> m2 = '1:35 PM'
    >>> in_time = datetime.strptime(m2, "%I:%M %p")
    >>> out_time = datetime.strftime(in_time, "%H:%M")
    >>> print(out_time)
    13:35

答案 2 :(得分:6)

试试这个:)

代码:

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

答案 3 :(得分:4)

time = raw_input().strip() # input format in hh:mm:ssAM/PM
t_splt = time.split(':')
if t_splt[2][2:] == 'PM' and t_splt[0] != '12':
    t_splt[0] = str(12+ int(t_splt[0]))
elif int(t_splt[0])==12 and t_splt[2][2:] == 'AM':
    t_splt[0] = '00'
t_splt[2] = t_splt[2][:2]
print ':'.join(t_splt)

答案 4 :(得分:1)

def timeConversion(s):
    if "PM" in s:
        s=s.replace("PM"," ")
        t= s.split(":")
        if t[0] != '12':
            t[0]=str(int(t[0])+12)
            s= (":").join(t)
        return s
    else:
        s = s.replace("AM"," ")
        t= s.split(":")
        if t[0] == '12':
            t[0]='00'
            s= (":").join(t)
        return s

答案 5 :(得分:0)

  

试试这个

class MyWindow : public Fl_Window {
public:
    MyWindow(int X,int Y,int W,int H, const char* title) : Fl_Window (X, Y, W, H, title) {}

    int handle(int e) {
        switch(e) {
            case FL_FOCUS:
                std::cout << "Window " << label() << " is focused" << std::endl;
                break;
            case FL_UNFOCUS:
                std::cout << "Window " << label() << " has lost focus" << std::endl;
                break;
        }
        return(Fl_Window::handle(e));
    }
};

int main() {
    MyWindow win1(100, 100, 200,200, "Window 1");
    win1.show();

    MyWindow win2(350, 100, 200,200, "Window 2");
    win2.show();

    return Fl::run();
}

答案 6 :(得分:0)

另一种干净的方式

def format_to_24hr(twelve_hour_time): return datetime.strftime( datetime.strptime( twelve_hour_time, '%Y-%m-%d %I:%M:%S %p' ), "%Y-%m-%d %H:%M:%S")

答案 7 :(得分:0)

不是使用“ H”来表示小时,而是使用示例下面的“ I”:

from datetime import *
m2 = 'Dec 14 2018 1:07PM'
m2 = datetime.strptime(m2, '%b %d %Y %I:%M%p')
print(m2)

请检查此link

答案 8 :(得分:0)

要将12小时制转换为24小时制

'''检查时间是'AM'还是'PM'以及时间是否以 12(中午或早晨)。如果时间是中午12点之后,那么我们添加
12,否则我们就这样保留它。如果时间是12 早上某事,我们将12转换为(00)'''

def timeConversion(s):

    if s[-2:] == 'PM' and s[:2] != '12':
        time = s.strip('PM')
        conv_time = str(int(time[:2])+12)+time[2:]

    elif s[-2:] == 'PM' and s[:2] == '12':
        conv_time = s.strip('PM')

    elif s[-2:] == 'AM' and s[:2] == '12':
        time = s.strip('AM')
        conv_time = '0'+str(int(time[:2])-12)+time[2:]

    else:
        conv_time = s.strip('AM')
        
    return conv_time

答案 9 :(得分:0)

最基本的方法是:

t_from_str_12h = datetime.datetime.strptime(s, "%I:%M:%S%p")
str_24h =  t_from_str.strftime("%H:%M:%S")

答案 10 :(得分:0)

#format HH:MM PM
def convert_to_24_h(hour):
    if "AM" in hour:
        if "12" in hour[:2]:
            return "00" + hour[2:-2]
        return hour[:-2]
    elif "PM" in hour:
        if "12" in hour[:2]:
            return hour[:-2]
    return str(int(hour[:2]) + 12) + hour[2:5]

答案 11 :(得分:-1)

%H小时(24小时制)作为零填充十进制数 %I小时(12小时制)作为零填充十进制数。

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "<b>%I</b>:%M")
print(m2)