-1

My input to this is in the format 07:05:09PM expected output:

19:05:09

output got:

19:5:9

def timeConversion(s):

    if "AM" in s:
        print(s[1:8])
    else:
        string=s.split(':')
        print(string)
        string.append(string[2][0:2])
        string.remove(string[2])
        print(string)
        date=list(map(int, string))
        print(date)
        a=date[0]+12
        b='%s:%s:%s' % (a, date[1], date[2])
        return b

My question is when I convert the date from string to int using map the zero is not picked up, is there any way to get the integer as such???

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 2
    If you care about leading zeros, you're not treating your data as integers. You're treating it as sequences of characters, and you shouldn't be calling `int` at all. – user2357112 Oct 17 '17 at 17:13
  • Your problem isn't with `map`, it's with how you're formatting your string. I'd start there :) – bendl Oct 17 '17 at 17:13

2 Answers2

0

If you don't want to use a custom function for formatting datetimes, you can get the intended output by formatting your string when you print it. Replace this line

b='%s:%s:%s' % (a, date[1], date[2])

with this:

b='%02d:%02d:%02d' % (a, date[1], date[2])
Brenden Petersen
  • 1,993
  • 1
  • 9
  • 10
0

there are functions for converting 24h to 12h time :

Load the string into a datetime object via strptime(), then dump via strftime() in the desired format:

from datetime import datetime
d = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
d  # d is a string '2016-04-28 07:46:32'
datetime.strptime(d, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S %p")
'2016-04-28 07:46:32 AM'

Note that the %I here is a 12-hour clock

Conversion of 24 hours date/time to 12 hours format and vice-versa

if you want to use your solution you can add leading zeros to integrs like in How to add Trailing zeroes to an integer :

numbers = [1, 19, 255]
numbers = [int('{:<03}'.format(number)) for number in numbers]

you can print leading zeros like in Display number with leading zeros

ralf htp
  • 9,149
  • 4
  • 22
  • 34