I\'m trying to convert times from 12 hour times into 24 hour times...
06:35 ## Morning
11:35 ## Morning (If m2 is anywhe
%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)
Try 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
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
''' 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
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
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")