首页 > 解决方案 > Converting user input to time and substracting it from main time

问题描述

I am doing some project for myself and i am stuck with an assignment.

I have strict time that's 30min
I have a user that gives an input like: 24008

I need to convert an user input to time(2min:40sec:08milisec) and substract it from main time. I tried time.strftime('%M:%S:%f', 1800) to show main Time (30min) like 30:00:00 but i don't seem to get the datetime or time imports and how do they work. Same with user input.

Can anyone with a kind heart would guide me to a right path on how to get this logic done and by what function?

I can't share a code because i don't have any working logic for this one.

标签: pythontimekivy

解决方案


datetime.time对象可能是为此使用的最佳数据结构

您的初始值 30 分钟将定义如下

import datetime
strict_time = datetime.time(minutes=30)

如果您作为示例给出的用户输入始终是输入格式,那么解析起来会有点困难,因为 python 的 datetime 模块的 strptime 行为不能处理 2 位数毫秒输入和 1 位数分钟输入。如果输入格式完全相同(5 位数字,1 分钟数字,2 秒数字和 2 毫秒数字),那么以下将起作用

user_input = '24008'
input_time = datetime.timedelta(
    minutes=int(user_input[0]),
    seconds=int(user_input[1:2]),
    microseconds=int(user_input[3:4])
)

new_time = strict_time - input_time

推荐阅读