How to convert AM/PM timestmap into 24hs format in Python?
Question:
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?
Answers:
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
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
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
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)
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
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)
%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)
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")
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
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 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
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")
#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]
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'))
# 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))
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
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?
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
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
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
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)
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
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)
%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)
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")
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
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 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
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")
#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]
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'))
# 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))
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