从中添加或减去时间的函数datetime.datetime.now现在()根据用户输入

2024-05-16 16:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须创建一个函数来计算时间。该函数应该能够接受三个参数,一个参数将提供实际的时间量,第二个参数可以接受什么时间单位,第三个参数将指示是否必须减去或添加当前时间。用户可以指定实际的时间单位是分钟还是小时。所以一个函数,如timecalc(1,h,+),将给我们一个小时的时间,如果它被调用为timecalc(1,h,-),它将给我们一个小时的时间。对函数的另一次调用作为time_calc(1,m,-)将计算分钟数。如何创建这样的函数?你知道吗

到目前为止我所知道的是

def time_sub_hour(difftime):
    now = datetime.datetime.now()
    lastHourDateTimeCompare = now - datetime.timedelta(hours=difftime)
    return lastHourDateTimeCompare.strftime('%H') + ' Hours '
print(time_sub_hour(1))

我希望输出为1小时,根据用户提供的


Tags: 函数用户参数datetimetimedef时间单位
2条回答

这就是我要找的,我必须改进它一些更返回准确的数字,所以如果它是计算下午4点(这是现在的时间)和下午2点(这是我们正在计算的函数),我希望函数返回2小时。我还想使它更具动态性,这样我们就不必传递“h”或“m”,而是在调用函数并相应地进行计算时,以某种方式计算出来。如有任何建议能使该职能更具活力,我将不胜感激。谢谢你的帮助。你知道吗

#the objective is to find the difference between two times and let the 
#user dictate if they want to add or reduce from the current time
  def add_timeDiff(time, value, ch):
        now = datetime.datetime.now()
        if ch == '+' and value =='h':
           raw_time = now + datetime.timedelta(hours=time)
           result = raw_time.strftime("%Y-%m-%d %H:%M:%S") 
        elif ch == '-' and value =='h':
            raw_time = now - datetime.timedelta(hours=time)
            result = raw_time.strftime("%Y-%m-%d %H:%M:%S") 
        return result

    print(add_timeDiff(1, 'h', '+'))
    print(add_timeDiff(1, 'h', '-'))

要构建一小时周期:

>>> import datetime
>>> datetime.timedelta(hours=1)

要构建一个90分钟的周期:

>>> datetime.timedelta(hours=1, minutes=30)

要从现有的datetime对象中添加或减去:

>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2019, 6, 13, 13, 19, 6, 15731)
>>> period_of_time = datetime.timedelta(hours=1.5)
>>> now + period_of_time
datetime.datetime(2019, 6, 13, 14, 49, 6, 15731)
>>> now - period_of_time
datetime.datetime(2019, 6, 13, 11, 49, 6, 15731)

相关问题 更多 >