1

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?

mx0
  • 6,445
  • 12
  • 49
  • 54

6 Answers6

3

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.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • is it better to use a lambda for this or just a function? – Abhishta Gatya Nov 25 '17 at 13:07
  • 1
    @AbhishtaGatya `lambda` is just a `one-line` way of defining a `function`, it is still just a `function`, so you could definitely do it if you wanted (see the most recent edit). – Joe Iddon Nov 25 '17 at 13:20
  • why is lambda not advisable? and i think you can fix the interger problem by converting the argument as a string using `str()` – Abhishta Gatya Nov 25 '17 at 13:23
  • The reason `lambda` is not advisable can be seen [in this question](https://stackoverflow.com/questions/134626/which-is-more-preferable-to-use-in-python-lambda-functions-or-nested-functions). Essentially, if you are assigning a `function` to a `variable` you should use `def` and if creating an anonymous `function` that is 'throw away' (e.g. as a `key` for sorting) you can use `lambda`. As for the `integer` problem, this cannot be fixed easily as you *can't* have an `integer` definition in Python3 with any leading zeros. So even `x = 08` is invalid and will throw an error. – Joe Iddon Nov 25 '17 at 13:28
1

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'
scrpy
  • 985
  • 6
  • 23
  • I would start with `number_str = str(number_str)`, so it works with both, numbers and strings. – Mr. T Nov 25 '17 at 12:55
  • @Piinthesky But, as @Joe Iddon points out, it's impossible to have the _integer_ `0730` — any leading zeroes are truncated, leaving `730`. So your suggestion would result in `number_str = '730'`, not `'0730'`. – scrpy Nov 25 '17 at 13:01
  • I know. It was just in case a number like `1023` is passed as an argument. But you are right, nobody would use this, because it doesn't work for all time points. – Mr. T Nov 25 '17 at 13:05
  • In fact, adding leading zeros can be done using string formatting: `number_str = '{:0>4}'.format(number)`, which when given `number = 730` or `number = '0730'` results in `'0730'`. – scrpy Nov 25 '17 at 13:13
  • Addendum: actually, attempting `number = 0730` does not truncate the leading zero, but throws a `SyntaxError` (in Python 3). – scrpy Nov 25 '17 at 13:32
1

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
sachin dubey
  • 755
  • 9
  • 28
0

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.

ahed87
  • 1,240
  • 10
  • 10
0
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")
yuki
  • 1
0

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)