python - 尝试在 Python 3 中将时间转换为整数

标签 python python-3.x datetime

我对 Python 和一般编程非常陌生,现在我已经在这个特定问题上工作了大约四个小时。 我正在尝试将时间(例如 12:30)转换为“if”语句中可用的时间。 这是我到目前为止所尝试过的:

time = input("Enter the time the call starts in 24-hour notation:\n").split(":")
if time >= 8:30 and time <= 18:00:
    print("YES")

当尝试执行该操作时,我收到无效语法错误。 当我尝试将时间转换为整数 [callTime = int(time)] 时,收到一条错误消息,指出

int() argument must be a string

这只是我正在解决的整个问题的一部分,但我想如果我能找到解决这个问题的起点,我就可以解决剩下的问题。 尽管我不相信我可以在这个特定问题上使用日期时间;任何事情都会有所帮助。

编辑:更正 int(time)

最佳答案

8:30 不是有效的数据类型。将其转换为整数以使其工作(8:30 = 8 小时 30 分钟 = 8*60+30 分钟)

>>> time = input("Enter the time the call starts in 24-hour notation:\n").split(":")
Enter the time the call starts in 24-hour notation:
12:30
>>> time
['12', '30'] # list of str
>>> time = [int(i) for i in time] # will raise an exception if str cannot be converted to int
>>> time
[12, 30] # list of int
>>> 60*time[0] + time[1] # time in minutes
750
>>> 

要以秒为单位获取它,例如 12:30:58,请使用 time_in_sec = time[0] * 3600 + time[1] * 60 + time[2 ] 在最后一行。

由于模数属性,可以保证只有一个“实际”时间对应于转换为整数的一小时。
对于您的问题,创建一个返回 int 的函数 to_integer(time_as_list),然后将用户输入与 to_integer('18:00'.split(':')) 进行比较和to_integer('8:30'.split(':'))

关于python - 尝试在 Python 3 中将时间转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251934/

相关文章:

python - 如何从 Python 扩展模块的 C 代码调用内置函数(或方法)?

python - 分组 Pandas : incompatible index of inserted column with frame index

python - 如何将每 500 个文件移动到不同的文件夹中

javascript - 如何根据 Django 中的表单输入向用户显示生成的图像?

python - 如何根据从 python 字符串中提取的数值按降序对记录进行排序?

python - Cython:如何制作具有不同签名的函数数组

c# - .ToShortDateString 返回与预期不同的文化格式

python - 将 np.gradient 与日期时间一起使用

C# Date Parse 非标准日期格式

python - 什么是 dict_keys、dict_items 和 dict_values?