我是 Python 初学者,我想尝试让 myslef 成为一段简单的代码,当我开始工作时,它会占用我的时间,并告诉我什么时候回家。
问题是输入格式,然后将这 8 个小时的工作添加到其中并有输出。
我可以让它与整数一起工作,但这还不够好。我想HH:MM
在 I/O 中看到格式
我在网上搜索了所有内容,但我发现的主要是关于一般时间的文章和建议(日期,更重要的是 datetime.now),而我需要它来理解我想输入我上班的时间和我上班的时间得到离开工作,不分天等。
# When do I get to go home program
# first we need ot define a variable to use it to store the time when I came
# to work
# That is atw (arrived to work)
# gh is "go home"
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
#atw = datetime.strptime(input('enter time you arrived to work in HHMM format: '), "%H%M")
h,m = map (int, time.split(":"))
#gh = atw (hour = h, minute = m)
print (("I came to work @", atw ,"%H%M"))
gh = atw + 0800
print ("You can go home @ ", gh)
各种错误消息,从语法到输入格式问题以及将这 8 个小时的工作添加到最终数字(gh
变量)
是否有一些很棒的东西可以让我了解如何真正让 python 理解我正在向变量添加时间,该变量应该被格式化为HH:MM
来自用户的时间()输入?
好的,让我们一步一步来,因为正如你所说,有各种各样的错误消息,从语法到......
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
前两行没有问题,这很好。
h,m = map (int, time.split(":"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'split'
哦,一个错误,让我们看看错误消息说的是什么:类型对象 'datetime.time' 没有属性 'split'。嗯,这是正确的,因为我们不想 split time
,但是我们给 input 的时间有 name atw
,所以让我们使用它:
h,m = map (int, atw.split(":"))
print (("I came to work @", atw ,"%H%M"))
没有错误,但输出奇怪:
('我来上班@', '08:17', '%H%M')
您可能不希望将元组作为输出(括号)并希望格式化该输出,正如我从格式 string 中看到的那样"%H%M"
。幸运的是,python (>=3.6) 有一个很好的解决方案,叫做f-strings:
print (f"I came to work @{atw}")
嗯,等等,格式化怎么样,它只输出我们输入的内容......所以使用h
and m
:
print (f"I came to work @{h:02d}:{m:02d}")
用谷歌搜索一下这:02d
意味着什么以及还有哪些其他选项;) 下一行:
gh = atw + 0800
File "<stdin>", line 1
gh = atw + 0800
^
SyntaxError: invalid token
嗯,你想增加 8 小时来获得结束时间,但你得到的只是一个语法错误......那是因为0800
没有有效的 python 构造,你可能只有 8小时?让我们试试这个...
gh = atw + 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
另一个错误,但为什么呢?您正在使用 atw,它是一个字符串,尽管您已经将其拆分为两个整数h
和m
,其中 h 代表小时:
gh = h + 8
print ("You can go home @ ", gh)
啊,该死的印刷品。查看上面并使用 f 字符串:
print (f"You can go home @{gh}:{m}")
现在试着看看你是否得到了使用strptime
@mkrieger1 在评论中建议的解决方案。和pleeeeease做一个python教程:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句