1

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?

Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
MMMMS
  • 2,179
  • 9
  • 43
  • 83
  • Possible duplicate of [How can I convert 24 hour time to 12 hour time?](https://stackoverflow.com/questions/13855111/how-can-i-convert-24-hour-time-to-12-hour-time) – Mayank Porwal Dec 11 '18 at 06:05

4 Answers4

6

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']
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
2

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']
Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
0

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']
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

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

Gelineau
  • 2,031
  • 4
  • 20
  • 30
SandiH
  • 1
  • 2