Python 从时间中减去小时和分钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46402022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:36:59  来源:igfitidea点击:

Subtract hours and minutes from time

pythonstringdatetimetime

提问by Sachhya

In my task what I need to do is to subtract some hours and minutes like (0:20,1:10...any value) from time (2:34 PM) and on the output side I need to display the time after subtraction. time and hrs:minutes value are hardcoded

在我的任务中,我需要做的是从时间(下午 2:34)中减去一些小时和分钟(0:20,1:10...任何值),在输出端我需要显示时间减法。time 和 hrs:minutes 值是硬编码的

Ex:

前任:

my_time = 1:05 AM

my_time = 1:05 AM

duration = 0:50

持续时间 = 0:50

so output should be 12:15 PM

所以输出应该是 12:15 PM

Output should be exact and in AM/PM Format and Applicable for all values [ 0:00 < Duration > 6:00 ]

输出应准确,采用 AM/PM 格式,适用于所有值 [ 0:00 < Duration > 6:00 ]

And don't care about seconds only hrs and minutes parts needed

并且不关心秒只需要几小时和几分钟的零件

回答by asfarto

from datetime import datetime, timedelta

d = datetime.today() - timedelta(hours=0, minutes=50)

d.strftime('%H:%M %p')

回答by Taniya

This worked for me :

这对我有用:

from datetime import datetime
s1 = '10:04:00'
s2 = '11:03:11' # for example
format = '%H:%M:%S'
time = datetime.strptime(s2, format) - datetime.strptime(s1, format)
print time

回答by Fuzed Mass

from datetime import datetime

d1 = datetime.strptime("01:05:00.000", "%H:%M:%S.%f")
d2 = datetime.strptime("00:50:00.000", "%H:%M:%S.%f")

print (d1-d2)