It is required to subtract from the given time, the present.

test = datetime.today().strftime("%H:%M") test2 = timedelta(hours=22, minutes=30) print(test-test2) 

It would seem simple, but in the final result I need to get only the number of minutes remaining until that time. Currently hung on this code. What can be done to make it work?

  • one
    It is not entirely clear what exactly you need, it is ребуется вычесть из заданного времени, настоящее. , and in the example you subtract 22 hours and 30 minutes from the current time (i.e., the specified time?). Please provide an example of input and output data. - froxxendsg
  • Example: we have a set time of 10:05 pm and there is a present time, that is, which is currently on the server, for example, it is 3:05 pm. Now we subtract the present time from the specified time and it turns out exactly 7 hours. But I think it would be better to translate this time into minutes, but this is not a problem. It may happen that the time will be negative and this should not cause problems. Is there any way to do this? - Aleksei .C
  • Those. as I understand, we work within the same day? Let the specified time be 22.05 , and the current (present) 23.35 , i.e. the answer will be negative -90 минут , how, then, to handle the answer, or is it no longer important? - froxxendsg pm

2 answers 2

Hope what you need. And I hope it is clear.

 >>> import math >>> from datetime import * >>> tmp = datetime.today(); >>> static_date = datetime(tmp.year, tmp.month, tmp.day, 22, 5); >>> static_date datetime.datetime(2019, 3, 17, 22, 5) >>> current_date = datetime.today() >>> current_date datetime.datetime(2019, 3, 17, 17, 2, 34, 792760) >>> delta = static_date - current_date >>> delta datetime.timedelta(seconds=18145, microseconds=207240) >>> # Если секунды нужно "отсекать", можно вместо math.ceil() юзать просто int(), тогда и библиотеку лишнюю подключать не придётся. >>> if ( delta.days == -1 ): out_minutes = math.ceil(delta.seconds / 60) - 24 * 60; else: out_minutes = math.ceil(delta.seconds / 60); >>> out_minutes 303 # Количество минут от текущего до заданного >>> test_date = datetime(tmp.year, tmp.month, tmp.day, 23, 35) >>> delta = static_date - test_date >>> delta datetime.timedelta(days=-1, seconds=81000) >>> if ( delta.days == -1 ): out_minutes = math.ceil(delta.seconds / 60) - 24 * 60; else: out_minutes = math.ceil(delta.seconds / 60); >>> out_minutes -90 # Отрицательное число, если текущее время больше заданного 

    If you use only hours and minutes, you can do this:

     test = datetime.today().hour * 60 + datetime.today().minute test2 = 22 * 60 + 30 print(test-test2) 

    In test, we have a number of minutes from 00:00 to the current time, and in test2 from 00:00 to 22:30