sruthi
sruthi

Reputation: 165

trying to insert character in the index of a string

i'm tring to insert 0 if hours are in single number(04) or if hours are in 24hours format then it should not be changed. I'm new to python. plz guide me.

current_time = '08:00'
lst = ['00:00','04:00','08:00','12:00','16:00','20:00']
if current_time in lst:
    hour, minute = current_time.split(':')
    if hour == '00':
        hour = '24'
    start_hour = int(hour)-4
    start_time = str(start_hour)+':'+'00'
    end_hour = int(hour)-1
    end_time = str(end_hour)+':'+'59'
    print(start_time,end_time)

I'm getting output like this:

4:00 7:59

but I'm expecting output like this

04:00 07:59

i've tried below approach

if len(start_time[0])==1:
    start_time = start_time[:0]+'0'+start_time[0:]

output:
016:00

Upvotes: 0

Views: 99

Answers (3)

Walker
Walker

Reputation: 11

You can try to use python f-strings, code likes below

start_time = f'{start_hour:02d}:00'
end_time = f'{end_hour:02d}:00'

Upvotes: 1

kcper
kcper

Reputation: 39

There is already function rjust(width, fillchar) built in Python, which will add padding to your string. Just change start_time = str(start_hour)+':'+'00' to start_time = str(start_hour).rjust(2, '0')+':'+'00' and it will add missing zero if needed.

Upvotes: 0

Cow
Cow

Reputation: 3030

This is the way to do it with zfill:

current_time = '08:00'
lst = ['00:00','04:00','08:00','12:00','16:00','20:00']
if current_time in lst:
    hour, minute = current_time.split(':')
    if hour == '00':
        hour = '24'
    start_hour = int(hour)-4
    start_time = str(start_hour).zfill(2)+':'+'00'
    end_hour = int(hour)-1
    end_time = str(end_hour).zfill(2)+':'+'59'
    print(start_time,end_time)

Result:

04:00 07:59

Upvotes: 1

Related Questions