I am trying to convert numbers into hours format like below,
numbers = [7,12,16,18]
Expected OP :
hours = ["07:00 AM","12:00 PM","04:00 PM","06:00 PM"]
Is there a way to achieve this?
I am trying to convert numbers into hours format like below,
numbers = [7,12,16,18]
Expected OP :
hours = ["07:00 AM","12:00 PM","04:00 PM","06:00 PM"]
Is there a way to achieve this?
Using the standard library:
import datetime
numbers = [7, 12, 16, 18]
hours = [datetime.time(num).strftime("%I:00 %p") for num in numbers]
# ['07:00 AM', '12:00 PM', '04:00 PM', '06:00 PM']
Try this:
import datetime
numbers = [7,12,16,18]
hours=[]
for i in numbers:
if i <= 12:
time = str(datetime.timedelta(hours=i)) +" AM"
else:
time = str(datetime.timedelta(hours=i-12)) + " PM"
hours.append(time)
print(hours)
OUTPUT:
['7:00:00 AM', '12:00:00 PM', '4:00:00 PM', '6:00:00 PM']
Not the cleanest way but will do the job:
numbers = [7,12,16,18]
hours = []
for n in numbers:
if n < 12:
if len(str(n)) == 1:
temp = "0"+str(n)+":00 AM"
else:
temp = str(n)+":00 AM"
else:
x = n - 12
if x == 0:
temp = "12:00 PM"
if len(str(x)) == 1:
temp = "0"+str(x)+":00 PM"
else:
temp = str(x)+":00 PM"
hours.append(temp)
Output:
['07:00 AM', '12:00 PM', '04:00 PM', '06:00 PM']
If I can use function to solve it:
def function(lst):
returned_list=[]
for item in lst:
end="AM"
if item >=12:
end="PM"
if item >12:
item-=12
if len(str(item))<2:
item='0'+str(item)
returned_list.append("{}:00 {}".format(item,end))
return returned_list
The program limitation is that it can only do from 0 to 23