在日期时间格式中使用 if 条件
Using if condition in datetime format
我被问到一个问题,要从用户那里获取两次输入作为函数(opening_time,closing_time),我必须确定时间之间的差异,但是如果这些值之一不是时间格式,returned 值应该是 -1.I 已经计算了时间差但是,我无法解决一个条件,如果任何一个变量不是时间格式,return-1。
拜托,我是编码新手,所以对任何错误表示歉意,请写出简单的解决方案,不要那么复杂。
from datetime import datetime
def compute_opening_duration(opening_time, closing_time):
str_format = "%H:%M:%S"
if opening_time or closing_time != datetime.time.str_format:
print(-1)
else:
tdelta = datetime.strptime(closing_time,str_format)
- datetime.strptime(opening_time,str_format)
print(tdelta)
试试这个 - 它会尝试使用您提供的字符串格式将输入转换为日期时间。如果其中任何一个失败,它将打印 -1.
from datetime import datetime
def compute_opening_duration(opening_time, closing_time):
str_format = "%H:%M:%S"
try:
t_open_time = datetime.strptime(closing_time,str_format)
t_closing_time = datetime.strptime(opening_time,str_format)
tdelta = datetime.strptime(closing_time,str_format) - datetime.strptime(opening_time,str_format)
print(tdelta)
except:
print(-1)
compute_opening_duration("04:10:21", "08:22:12")
我被问到一个问题,要从用户那里获取两次输入作为函数(opening_time,closing_time),我必须确定时间之间的差异,但是如果这些值之一不是时间格式,returned 值应该是 -1.I 已经计算了时间差但是,我无法解决一个条件,如果任何一个变量不是时间格式,return-1。 拜托,我是编码新手,所以对任何错误表示歉意,请写出简单的解决方案,不要那么复杂。
from datetime import datetime
def compute_opening_duration(opening_time, closing_time):
str_format = "%H:%M:%S"
if opening_time or closing_time != datetime.time.str_format:
print(-1)
else:
tdelta = datetime.strptime(closing_time,str_format)
- datetime.strptime(opening_time,str_format)
print(tdelta)
试试这个 - 它会尝试使用您提供的字符串格式将输入转换为日期时间。如果其中任何一个失败,它将打印 -1.
from datetime import datetime
def compute_opening_duration(opening_time, closing_time):
str_format = "%H:%M:%S"
try:
t_open_time = datetime.strptime(closing_time,str_format)
t_closing_time = datetime.strptime(opening_time,str_format)
tdelta = datetime.strptime(closing_time,str_format) - datetime.strptime(opening_time,str_format)
print(tdelta)
except:
print(-1)
compute_opening_duration("04:10:21", "08:22:12")