user8590679
user8590679

Reputation:

How to convert number to time in python?

I need convert number to time.

For example:

I need to convert 1230 to 12:30 or 0730 to 07:30.

How to convert a number to time in python?

Upvotes: 1

Views: 17371

Answers (6)

All of these require 4 digits for your time. This code will add a zero to the front if there are 3 digits. It will check for invalid times.

def conv_num_time(time):
num_str = ('{:04}'.format(time))
time_str = num_str[:2] + ':' + num_str[2:]
if int(num_str[:2])>23 or int(num_str[2:])>59:
    print("Invalid time")
else:
    print(time_str)
user_time = int(input(': '))
conv_num_time(user_time)

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20434

We can create a function that takes a string and returns the time.

This can all be done in one line by slicing the string up to the minutes (done with [:2]) and then concatenating a ':' and finally concatenating the minutes with [2:].

def getTime(t):
    return t[:2] + ':' + t[2:]

and some tests to show it works:

>>> getTime("1230")
'12:30'
>>> getTime("0730")
'07:30'
>>> getTime("1512")
'15:12'

Note how the function cannot take an integer and convert this to a string, as otherwise entries with leading zeros would fail. E.g. 0730 wouldn't work.


Yes, to answer @AbhishtaGatya, this could be written using a lambda function, but doing so wouldn't be advisable. However:

getTime = lambda t: t[:2] + ':' + t[2:]

works just the same as above.

Upvotes: 3

yuki
yuki

Reputation: 1

from datetime import datetime

t1="1205"
t2="0605PM"
#%I - 12 hour format
print t1,(datetime.strptime(t1,"%I%M")).strftime("%I:%M")
print t2,(datetime.strptime(t2,"%I%M%p")).strftime("%I:%M")

#%H - 24 hour format
print t1,(datetime.strptime(t1,"%I%M")).strftime("%H:%M") 
print t2,(datetime.strptime(t2,"%I%M%p")).strftime("%H:%M")

Upvotes: 0

scrpy
scrpy

Reputation: 1021

Assuming the input is a string, you can do this:

number_str = '0730'
time_str = number_str[:2] + ':' + number_str[2:]
print(time_str)  # Output: '07:30'

Upvotes: 1

sachin dubey
sachin dubey

Reputation: 779

You can insert ":" to the index 2

val = 1230
new= ([str(i) for i in str(val)])
new.insert(2,":")

print(''.join(new))

output:

12:30

Upvotes: 1

ahed87
ahed87

Reputation: 1360

If you are sure that you only have 4 digits as strings one way is

new = '%s:%s'%(string[:2], string[2:])

Recommended is however to use the datetime handling within python datetime.

Upvotes: 0

Related Questions