簡體   English   中英

如何從日期時間對象中提取小時/分鍾並去掉年/月/日/秒部分?

[英]How do I extract the Hour/Minute from a datetime object and get rid of the Year/Month/Day/Second section?

我正在編寫一個程序來跟蹤我作為廚師的工作時間。 我正在尋找它來詢問我什么時候開始、結束以及那天我休息了多長時間。 我遇到的問題是我在第 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM