【问题标题】:Convert 12 hour into 24 hour times将 12 小时转换为 24 小时时间
【发布时间】:2013-10-14 06:47:57
【问题描述】:

我正在尝试将时间从 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")

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

【问题讨论】:

  • 字符串"1:35" 中没有任何内容表明现在是下午时间,因此strptime() 将假定现在是上午。要表示下午,您需要某种上午/下午指示器。
  • SO 13855111主要是逆问题,将24小时制转换为12小时制。
  • @JonathanLeffler 问题是我不能自动将 PM 添加到字符串时间?如果 m2 值是 10:00 到 12:00,而实际时间是 10:00 到 13:00(早上到下午 1 点),那么 m2 应该被认为是早上时间,其他一切都应该被认为是下午时间。跨度>
  • 如果你有决定时间是上午还是下午的规则,你需要将它们写在代码中。 Python 无法读懂你的想法。

标签: python python-2.7 time


【解决方案1】:

此方法使用带有格式指令的 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】:

    您需要指定您的意思是 PM 而不是 AM。

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

    【讨论】:

    • 另外,他需要strftime 才能得到他想要的输出。
    • @dan04 我的字符串 (m2) 是在别处自动生成的,我无法在它们上添加“PM”。我已经编辑了我的原始帖子以显示我的一些时间..
    【解决方案3】:

    试试这个:)

    代码:

    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
    

    【讨论】:

    • 我知道这是一个旧答案,但为什么你的格式字符串是三重引号?同样m2 已经是一个字符串,你可以写m2 += " AM"。您还在m2 &gt;= "10:00" 中进行字符串比较。为什么这个答案被接受...
    【解决方案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)
    

    【讨论】:

      【解决方案5】:

      如果日期采用这种格式(HH:MM:SSPM/AM),则以下代码有效:

      a=''
      def timeConversion(s):
         if s[-2:] == "AM" :
            if s[:2] == '12':
                a = str('00' + s[2:8])
            else:
                a = s[:-2]
         else:
            if s[:2] == '12':
                a = s[:-2]
            else:
                a = str(int(s[:2]) + 12) + s[2:8]
         return a
      
      
      s = '11:05:45AM'
      result = timeConversion(s)
      print(result)
      

      【讨论】:

      • 优雅作为一种实际算法,不使用很多内置函数。
      【解决方案6】:

      试试这个?

      dicti = 
      {'01':13,'02':14,'03':15,'04':16,'05':17,'06':18,'07':19,'08':20,'09':21,'10':22,'11':23,'12':12}
      s = '12:40:22PM'
      if s.endswith('AM'):
      if s.startswith('12'):
          s1=s[:8]
          bb=s1.replace('12','00')
          print bb
      else:
          s1=s[:8]
          print s1
      else:
      s1=s[:8]
      time= str(s[:2])
      ora=str(dicti[time])
      aa=s1.replace(time,ora)
      print aa
      

      【讨论】:

        【解决方案7】:

        另一种干净利落的方法

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

        【讨论】:

          【解决方案8】:
          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
          

          【讨论】:

          • 这实际上是最简单的方法。不错!
          【解决方案9】:

          不要使用“H”表示小时,而是使用“I”,如下面的示例中所述:

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

          请查看link

          【讨论】:

            【解决方案10】:

            将 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
            

            【讨论】:

            • 如果您对解决方案的作用有最少的解释,这将很有帮助。
            【解决方案11】:

            最基本的方式是:

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

            【讨论】:

              【解决方案12】:
              #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]
              

              【讨论】:

              【解决方案13】:

              由于大部分手动计算似乎有点复杂,我分享一下我的做法。

              # Assumption: Time format (hh:mm am/pm) - You can add seconds as well if you need
              def to_24hr(time_in_12hr):
                  hr_min, am_pm = time_in_12hr.lower().split()
                  hrs, mins = [int(i) for i in hr_min.split(":")]
                  hrs %= 12
                  hrs += 12 if am_pm == 'pm' else 0
                  return f"{hrs}:{mins}"
              
              print(to_24hr('12:00 AM'))
              

              【讨论】:

                【解决方案14】:

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

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

                【讨论】:

                • %H 小时(24 小时制)作为零填充十进制数。
                  %I 小时(12 小时制),用零填充的十进制数表示。 m2 = "1:35" ## 这是下午。 m2 = datetime.strptime(m2, "%I:%M") 打印(m2)
                • 虽然此代码 sn-p 可以解决问题,但 including an explanation 有助于提高您的回复质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
                猜你喜欢
                • 2012-04-09
                • 1970-01-01
                • 2012-12-01
                • 2021-12-24
                • 1970-01-01
                • 2017-06-27
                • 2016-12-19
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多