Get time in minutes python

Преобразование времени в часы, минуты и секунды в Python

В этом уроке мы будем говорить о времени. Рассмотрим различные способы преобразования времени в секундах во время в часах, минутах и секундах.

Двигаясь вперед, мы будем называть время в часах, минутах и секундах предпочтительным форматом.

Давайте потратим немного «времени» и подумаем о проблеме. Несомненно, у python есть удивительные модули, которые могут сделать преобразование за нас. Но давайте сначала попробуем написать нашу собственную программу, прежде чем мы перейдем к встроенным модулям.

Создание пользовательской функции

Чтобы написать нашу собственную функцию преобразования, нам сначала нужно подумать о проблеме математически.

Как перевести секунды в предпочтительный формат? Вам нужно получить значение часов, минут и секунд.

Предположим, что время в секундах не превышает общего количества секунд в сутках. Если это так, мы разделим его на общее количество секунд в день и возьмем остаток.

Математически это представлено как:

seconds = seconds % (24 * 3600)

24 * 3600, поскольку в одном часе 3600 секунд (60 * 60), а в одном дне 24 часа.

Читайте также:  Class file location in java

После этого мы можем продолжить и вычислить значение часа из секунд.

1. Как получить значение часа?

Чтобы получить значение часа из секунд, мы будем использовать оператор деления (//). Он возвращает целую часть частного.

Поскольку нам нужно количество часов, мы разделим общее количество секунд (n) на общее количество секунд в часе (3600).

Математически это представлено как:

После этого нам нужно посчитать минуты.

2. Как получить значение минуты?

Чтобы вычислить значение минут, нам нужно сначала разделить общее количество секунд на 3600 и взять остаток.

Математически это представлено как:

Теперь, чтобы вычислить значение минут из приведенного выше результата, мы снова будем использовать оператор floor.

В минуте шестьдесят секунд, поэтому мы уменьшаем значение секунд до 60.

После вычисления значения минут мы можем перейти к вычислению значения секунд для нашего предпочтительного формата.

3. Как получить значение секунд?

Чтобы получить значение секунд, нам снова нужно разделить общее количество секунд на количество секунд в одной минуте (60) и взять остаток.

Математически это делается следующим образом:

Это даст второе значение, которое нам нужно для нашего предпочтительного формата.

4. Полный код

Давайте скомпилируем вышеупомянутые знания в функции Python.

def convert_to_preferred_format(sec): sec = sec % (24 * 3600) hour = sec // 3600 sec %= 3600 min = sec // 60 sec %= 60 print("seconds value in hours:",hour) print("seconds value in minutes:",min) return "%02d:%02d:%02d" % (hour, min, sec) n = 10000 print("Time in preferred format :-",convert(n))
seconds value in hours: 2 seconds value in minutes: 46 Time in preferred format :- 02:46:40

Использование модуля времени

Теперь давайте посмотрим на встроенный модуль, который позволяет нам конвертировать секунды в наш предпочтительный формат в одной строке кода.

Модуль времени определяет эпоху как 1 января 1970 года, 00:00:00 (UTC) в системах Unix (зависит от системы). Эпоха – это, по сути, начало времени для компьютера. Думайте об этом как о floor 0. Всякий раз, когда мы конвертируем секунды с помощью модуля времени, эта эпоха используется как точка отсчета.

Чтобы вывести эпоху в вашей системе, используйте следующую строку кода:

Time Epoch

Чтобы преобразовать секунды в предпочтительный формат, используйте следующую строку кода:

time.strftime("%H:%M:%S", time.gmtime(n))

Эта строка принимает время в секундах как «n», а затем позволяет отдельно выводить часы, минуты и секунды.

Полный код Python выглядит следующим образом:

import time n=10000 time_format = time.strftime("%H:%M:%S", time.gmtime(n)) print("Time in preferred format :-",time_format)
Time in preferred format :- 02:46:40

Модуль времени также дает вам возможность отображать дополнительную информацию, такую как день, месяц и год.

% а Отображать сокращенное название дня недели.
% А Отображать полное название дня недели.
% b Отображать сокращенное название месяца.
% B Отображать полное название месяца.
% c Отобразить соответствующее представление даты и времени.
% d Отображать день месяца как десятичное число [01,31].

Попробуем использовать% a и % b.

import time n=100000000000 time_format = time.strftime("Day: %a, Time: %H:%M:%S, Month: %b", time.gmtime(n)) print("Time in preferred format :-",time_format)
Time in preferred format :- Day: Wed, Time: 09:46:40, Month: Nov

Использование модуля Datetime

Вы также можете использовать метод timedelta в модуле DateTime для преобразования секунд в предпочтительный формат.

Он отображает время в днях, часах, минутах и секундах, прошедших с эпохи.

Код Python для преобразования секунд в предпочтительный формат с использованием модуля Datetime выглядит следующим образом:

import datetime n= 10000000 time_format = str(datetime.timedelta(seconds = n)) print("Time in preferred format :-",time_format)
Time in preferred format :- 115 days, 17:46:40

Заключение

В этом руководстве были рассмотрены три различных способа преобразования секунд в часы, минуты и секунды. В целом есть два разных способа решения проблемы.

Вы либо пишете свою собственную функцию, либо используете встроенный модуль. Мы начали с написания нашей собственной функции, а затем посмотрели на модуль времени и DateTime.

Источник

Convert time into hours minutes and seconds in Python

Convert time into hours minutes and seconds in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this tutorial, we will be talking about time. Don’t worry, this isn’t a boring history tutorial, rather we will be looking at different ways of converting time in seconds to time in hours, minutes, and seconds. Moving forwards we will be referring to time in hours, minutes and seconds as time in the preferred format. It will look like :

Let’s take some ‘time’ and think about the problem at hand. No doubt python has amazing modules to do the conversion for us. But let’s try and write our own program first before we move on to the in-built modules.

Building a Custom function to convert time into hours minutes and seconds

To write our own conversion function we first need to think about the problem mathematically. How do you convert seconds into the preferred format? You need to get the value of hours, minutes and seconds. We are going to assume that the time in seconds doesn’t exceed the total number of seconds in a day. If it does we will divide it with the total number of seconds in a day and take the remainder. This is mathematically represented as :

seconds = seconds % (24 * 3600) 

% operator gives the remainder. 24*3600 since one hour has 3600 seconds (60*60) and one day has 24 hours. After this we can proceed and calculate the hour value from seconds.

1. Get the hour value

To get the hour value from seconds we will be using the floor division operator (//). It returns the integral part of the quotient. Since we need the number of hours, we will divide the total number of seconds (n) by the total number of seconds in an hour (3600). Mathematically this is represented as :

2. Get the minute value

To calculate the value of minutes we need to first divide the total number of seconds by 3600 and take the remainder. Mathematically this is represented as :

A minute has sixty seconds hence we floor the seconds value with 60. After calculating minute value we can move forward to calculate the seconds’ value for our preferred format.

3. Get the seconds value

To get seconds value we again need to divide the total number of seconds by the number of seconds in one minute (60) and take the remainder. Mathematically this is done as follows :

4. Complete code

def convert_to_preferred_format(sec): sec = sec % (24 * 3600) hour = sec // 3600 sec %= 3600 min = sec // 60 sec %= 60 print("seconds value in hours:",hour) print("seconds value in minutes:",min) return "%02d:%02d:%02d" % (hour, min, sec) n = 10000 print("Time in preferred format :-",convert(n)) 
seconds value in hours: 2 seconds value in minutes: 46 Time in preferred format :- 02:46:40 

Using the Time module

Now let’s look at an inbuilt module that lets us convert seconds into our preferred format in one line of code. The time module defines the epoch as January 1, 1970, 00:00:00 (UTC) in Unix systems (system dependent). Epoch is basically the start of time for a computer. Think of it as day 0. Whenever we convert seconds using the time module, this epoch is used as the reference point. To output the epoch in your system, use the following line of code :

Time Epoch

To convert seconds into preferred format use the following line of code:

time.strftime("%H:%M:%S", time.gmtime(n)) 

This line takes the time in seconds as ‘n’ and then lets you output hour, minute, and second value separately. The complete python code is as follows:

import time n=10000 time_format = time.strftime("%H:%M:%S", time.gmtime(n)) print("Time in preferred format :-",time_format) 
Time in preferred format :- 02:46:40 

The time module also gives you the option to display some extra information such as day, month, and year.

%a display abbreviated weekday name.
%A display full weekday name.
%b display abbreviated month name.
%B display full month name.
%c display the appropriate date and time representation.
%d display day of the month as a decimal number [01,31].
import time n=100000000000 time_format = time.strftime("Day: %a, Time: %H:%M:%S, Month: %b", time.gmtime(n)) print("Time in preferred format :-",time_format) 
Time in preferred format :- Day: Wed, Time: 09:46:40, Month: Nov 

Using Datetime module

You can also use the timedelta method under the DateTime module to convert seconds into the preferred format. It displays the time as days, hours, minutes, and seconds elapsed since the epoch. The python code to convert seconds into the preferred format using Datetime module is as follows:

import datetime n= 10000000 time_format = str(datetime.timedelta(seconds = n)) print("Time in preferred format :-",time_format) 
Time in preferred format :- 115 days, 17:46:40 

Conclusion

This tutorial looked at three different ways you can use to convert seconds into hours, minutes, and seconds. Broadly there are two different ways to go about the problem. Either you write your own function or use an inbuilt module. We started by writing our own function and then looked at the time and DateTime module.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Convert time into hours minutes and seconds in Python With Examples [Latest]

Convert time into hours minutes and seconds in Python With Examples

In this tutorial, we will be talking about time. Don’t worry, this isn’t a boring history tutorial, rather we will be looking at different ways of converting time in seconds to time in hours, minutes, and seconds.

Moving forwards we will be referring to time in hours, minutes and seconds as time in the preferred format.

Let’s take some ‘time’ and think about the problem at hand. No doubt python has amazing modules to do the conversion for us. But let’s try and write our own program first before we move on to the in-built modules.

Building a Custom function to convert time into hours minutes and seconds

To write our own conversion function we first need to think about the problem mathematically.

How do you convert seconds into the preferred format?

You need to get the value of hours, minutes and seconds.

We are going to assume that the time in seconds doesn’t exceed the total number of seconds in a day. If it does we will divide it with the total number of seconds in a day and take the remainder.

This is mathematically represented as :

Источник

Оцените статью