用文字制作一个时钟

时间:2015-03-23 18:50:33

标签: python time

我正在尝试制作一个时钟,根据时间的不同输出当前时间。一些例子是:

  • 如果时间是上午11:30,则应打印出“已经过了十一点半”
  • 如果时间是11:50 - 11:59,它应该打印'很快就是十二点'

目前的代码如下所示:

from time import *
from num2words import num2words as n2w

Soon = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
HalfPast = [30]
JustAfter = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

curr_time = strftime('%H:%M:%S', localtime())
curr_time_str = curr_time.split(':')
standard_phrase = "It's "
special_word = 'Nope'
ampm = strftime('%p', localtime())
ampm = ampm.lower()
ampm = ampm.title()
def check_time():
    for x in curr_time_str[1]:
        if int(x) in Soon:
            special_word = 'soon '
        elif int(x) in HalfPast:
            special_word = 'half past '
        elif int(x) in JustAfter:
            special_word = 'just after '
        else:
            pass
    return special_word

if check_time() != 'Nope':
    print(standard_phrase + check_time() + n2w(int(curr_time_str[0])).title() + ' ' + ampm)
elif check_time() == 'Nope':
    print(standard_phrase + n2w(int(curr_time_str[0])) + ':' + n2w(int(curr_time_str[1])))
else:
    exit()

我知道它不是最好的代码,但它看起来像是用于调试。

1 个答案:

答案 0 :(得分:3)

问题实际上非常简单。让我们看看发生了什么:

在我写这篇文章时,这是我的本地值curr_time_str

>>> curr_time_str
['19', '57', '05']

现在,在check_time您正在查看curr_time_str[1]

>>> curr_time_str[1]
'57'

这是一个字符串;而你实际上正在遍历该字符串:

>>> for x in curr_time_str[1]:
        print(x)

5
7

所以你得到57。这两个都在JustAfter,因此您返回'just after '

这实际上发生在每个数字上,因为毕竟,如果你只看一个数字,你总是低于10,因此总是在JustAfter内。所以你试图做的是查看curr_time_str[1]的全部价值:

def check_time():
    x = int(curr_time_str[1])
    if x in Soon:
        special_word = 'soon '
    elif x in HalfPast:
        special_word = 'half past '
    elif x in JustAfter:
        special_word = 'just after '
    return special_word