如何从datetime对象中提取Hour/Minute并去掉Year/Month/Day/Second部分



我正在编写一个程序来跟踪我作为厨师的工作时间。我想问一下我什么时候开始,什么时候结束,那天休息了多久。我遇到的问题是,我在第12行(time data '1900-01-01 10:00:00' does not match format '%H:%M'(上不断收到一个值错误,并且在这里应用试图解释我自己问题的解决方案的线程时遇到了问题。我知道我需要做的是从datetime对象中提取一些数据,但到目前为止,我所尝试的一切都出现了错误。

下面的代码;

from datetime import datetime
fmt = "%H:%M"  # The time format i.e hours and minutes
print("Please input your starting and finishing times for the following days.")
print("Wednesday:")  # Denotes which day is being asked about
wed_start_in = (input("What time did you start?")) # asks starting time
wed_start = str(datetime.strptime(wed_start_in, "%H:%M"))  # converts time start input into a datetime object
wed_finish_in = (input("And what time did you finish?"))  # asks finishing time
wed_finish = str(datetime.strptime(wed_start_in, "%H:%M"))
wed_hours = datetime.strptime(wed_start, fmt) - datetime.strptime(wed_finish, fmt)
print(wed_hours)

您正在将来回转换为字符串;相反,将每个时间解析一次,然后将其保留为时间。只在最后将它们转换回字符串(如果需要(。

wed_start_in = input("What time did you start?") # asks starting time
wed_start = datetime.strptime(wed_start_in, "%H:%M")  # converts time start input into a datetime object
wed_finish_in = input("And what time did you finish?")  # asks finishing time
wed_finish = datetime.strptime(wed_finish_in, "%H:%M")
wed_hours = wed_finish - wed_start
print(wed_hours)

最新更新