31

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

Automatic Example 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

Example code:

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

Expected Output:

13:35

Actual Output:

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?

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
Ryflex
  • 5,559
  • 25
  • 79
  • 148
  • http://stackoverflow.com/questions/13855111/convert-24-hours-time-to-12-hours-in-python – The Humble Rat Oct 07 '13 at 15:54
  • 9
    There is nothing in the string `"1:35"` to indicate that it is an afternoon time, so `strptime()` will assume it is morning. To indicate afternoon, you'd need an am/pm indicator of some sort. – Jonathan Leffler Oct 07 '13 at 15:54
  • [SO 13855111](http://stackoverflow.com/q/13855111) is mainly about the converse problem, converting 24 hour to 12 hour time. – Jonathan Leffler Oct 07 '13 at 15:55
  • @JonathanLeffler The problem is I can't automatically add the PM to the string time? If the m2 value is 10:00 to 12:00 and the real life time is 10:00 to 13:00 (morning to 1pm) then m2 should be considered a morning time, everything else should be considered an afternoon time. – Ryflex Oct 07 '13 at 16:21
  • 1
    If you have rules for deciding whether a time is AM or PM, you need to write them in code. Python can't read your mind. – dan04 Oct 07 '13 at 16:31
  • @dan04 I just made the said rules to get around this problem... – Ryflex Oct 07 '13 at 16:33

16 Answers16

47

This approach uses strptime and strftime with format directives as per https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior, %H is the 24 hour clock, %I is the 12 hour clock and when using the 12 hour clock, %p qualifies if it is AM or 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
modpy
  • 701
  • 8
  • 8
33

You need to specify that you mean PM instead of AM.

>>> from datetime import *
>>> m2 = '1:35 PM'
>>> m2 = datetime.strptime(m2, '%I:%M %p')
>>> print(m2)
1900-01-01 13:35:00
dan04
  • 87,747
  • 23
  • 163
  • 198
  • 2
    Plus, he needs `strftime` to get his desired output. – Robᵩ Oct 07 '13 at 15:59
  • @dan04 my strings (m2) are automatically generated elsewhere, I can't add "PM" onto them. I've edited my original post to show some of my times.. – Ryflex Oct 07 '13 at 16:13
  • This should be the answer, indeed. Other answers are clones and some others, achieve the result, but using extra computations and resources, unnecessary in comparison to what this proposal is offering. – ivanleoncz Jun 27 '22 at 17:15
7

Try this :)

Code:

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

Output:

13:35
SMNALLY
  • 1,361
  • 3
  • 14
  • 23
  • 3
    I know this is an old answer, but why are your format strings triple quoted? Also `m2` is a string already, you could just write `m2 += " AM"`. Also you're doing string comparisons in `m2 >= "10:00"`. Why is this answer accepted... – Enrico Borba Jul 11 '18 at 00:21
5

If date is in this format (HH:MM:SSPM/AM) the following code is effective :

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)
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
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)
NagMani
  • 41
  • 2
2

Try this

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
2
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
jugesh
  • 70
  • 6
1

One more way to do this cleanly

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

Alok Kumar Singh
  • 2,331
  • 3
  • 18
  • 37
0

Instead of using "H" for hour indication use "I" as described in the example bellow:

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

Please check this link

0

To convert 12 hour time format into 24 hour time format

''' To check whether time is 'AM' or 'PM' and whether it starts with 12 (noon or morning). In case time is after 12 noon then we add
12 to it, else we let it remain as such. In case time is 12 something in the morning, we convert 12 to (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
Ishaan
  • 1
  • 1
0

the most basic way is:

t_from_str_12h = datetime.datetime.strptime(s, "%I:%M:%S%p")
str_24h =  t_from_str.strftime("%H:%M:%S")
AgE
  • 387
  • 2
  • 8
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]
  • Use 4 spaces per indentation level. See [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#indentation) – AcK Jan 08 '21 at 16:56
0

Since most of the manual calculation seems a bit complicated, I am sharing my way of doing it.

# 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'))
0
# 12-hour to 24-hour time format
import re

s = '12:05:45PM'


def timeConversion(s):
    hour = s.split(':')
    lastString = re.split('(\d+)', hour[2])
    if len(hour[2]) > 2:
        hour[2] = lastString[1]
    if 'AM' not in hour or 'am' not in hour or int(hour[0]) < 12:
        if (lastString.__contains__('PM') and int(hour[0]) < 12) or (lastString.__contains__('pm') and int(hour[0]) < 12):
            hour[0] = str(int(hour[0]) + 12)
    if hour[0] == '12' and (lastString.__contains__('AM') or lastString.count('am')):
        hour[0] = '00'
    x = "{d}:{m}:{y}".format(d=hour[0], m=hour[1], y=hour[2])
    return x


print(timeConversion(s))
Nik's
  • 21
  • 4
0

Here's my solution by using python builtin functions to convert 12-hour time format into 24-hour time format

def time_conversion(s):
    if s.endswith('AM') and s.startswith('12'):
        s = s.replace('12', '00')
    if s.endswith('PM') and not s.startswith('12'):
        time_s = s.split(':')
        time_s[0] = str(int(time_s[0]) + 12)
        s = ":".join(time_s)
        
    s = s.replace('AM', '').replace('PM', '')
    
    return s
          
time_conversion('07:05:45PM') 

19:05:45
-1

%H Hour (24-hour clock) as a zero-padded decimal number.
%I Hour (12-hour clock) as a zero-padded decimal number.

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "<b>%I</b>:%M")
print(m2)
Skandix
  • 1,916
  • 6
  • 27
  • 36
szerem
  • 1
  • 1
  • %H Hour (24-hour clock) as a zero-padded decimal number.
    %I Hour (12-hour clock) as a zero-padded decimal number. m2 = "1:35" ## This is in the afternoon. m2 = datetime.strptime(m2, "%I:%M") print(m2)
    – szerem Apr 06 '18 at 17:19
  • While this code snippet may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) helps to improve the quality of your response. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Stefan Crain Apr 06 '18 at 17:52