# Expressing current time with natural language

def current_time():
'''Returns a tuple containing (hour, minute) for current local time.'''
import time
local_time = time.localtime(time.time())
return (local_time.tm_hour, local_time.tm_min)

(hour,minute) = current_time()

def ishtime(hour, minute):
import random

Starting_str = ['it is','its',"it's","Current time is"]

h_str = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']

mid_str = ['almost','nearly','roughly','maybe']

Ex = ['Exactly' , 'Perpectly' ,'']

m_str = ['ten','twenty','thirty','fourty','fifty']

End_str = ['in the morning','in the afternoon','in the evening','at night']

## - define random strings

Mid = mid_str[int(random.random()*4)]

Hour = h_str[(int(hour)-1)%12]

if round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
Rand_m_str = ''
else:
Rand_m_str = m_str[int((round(int(minute),-1)/10))-1]

## -define for final ex)its , it's , almost, one two three..

if int(hour)>=6 and int(hour)<13:
Ending = End_str

elif int(hour)>=13 and int(hour)<19:
Ending = End_str

elif int(hour)>=19 and int(hour)<=23:
Ending = End_str

elif int(hour)>=0 and int(hour)<6:
Ending = End_str

## - define 'ending str' ex) in the morning

if minute == 0 or minute == 00:
Result = "%s %s 'o clock %s" %(Head,Hour,Ending)

elif minute%10 == 0:
Result = "%s %s %s after %s %s" %(Head,Ex[int(random.random()*4)],Rand_m_str,Hour,Ending)

elif round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
Result = "%s %s %s%s %s" %(Head,Mid,Rand_m_str,Hour,Ending)

else:
Result = "%s %s %s minute after %s %s" %(Head,Mid,Rand_m_str,Hour,Ending)

return Result

print ishtime(hour,minute)


I did this job.. how could i make it simpler?

• You could start by removing "its" and fixing "Perpectly" and capitalization. – Junuxx Dec 13 '13 at 9:07
• Why not the builtin datetime.datetime.strftime? – Patrick Collins Dec 21 '13 at 10:37

Python supports double-ended inequalities:

End_str = ['at night', 'in the morning','in the afternoon','in the evening']

if 0 <= hour < 6:
Ending = End_str
elif 6 <= hour < 13:
Ending = End_str
elif 13 <= hour < 19:
Ending = End_str
elif 19 <= hour < 24:
Ending = End_str


I've changed 23 to 24 for consistency and rearranged the members of End_str. I don't see how hour should be anything other than an integer, so I've removed the casts.

if minute == 0 or minute == 00 is redundant, since 00 is exactly the same as 0.

I would expect noon and midnight to be handled as special cases.

Avoid constructs like Ex[int(random.random()*4)] which are brittle at several levels:

• What if Ex is changed to no longer contain 4 elements?
• Hey, it already only has 3 elements.
• Fixing that by using len(Ex) is still quite verbose.

Prefer random.choice, using it like this: random.choice(Ex)