converts from timedelta into minutes

  • Last Update :
  • Techknowledgy :

We can follow the same logic to convert a timedelta to hours. Instead of dividing the total_seconds() by the number of seconds in a minute, or dividing thetimedelta object by timedelta(minutes=1), we do it for hour.,the first one you divide the total_seconds() by the number of seconds in a minute, which is 60,A timedelta has only one method called timedelta.total_seconds(). This method returns the total number of seconds the duration has. If we want to convert a timedelta object to seconds, we can just call it.,the second approach, you divide the timedelta object by timedelta(minutes=1)

Since timedelta represents a duration, we can use it to add days to a datetime. The number of can be positive or negative, thus allowing us to create a date in the future or in the past. The code snippet below shows an example.

>>>
import datetime

   >>>
   now = datetime.datetime.now()

   >>>
   now
datetime.datetime(2020, 11, 3, 22, 5, 21, 979147)

   >>>
   from datetime
import timedelta

   >>>
   now + timedelta(days = 3)
datetime.datetime(2020, 11, 6, 22, 5, 21, 979147)

   >>>
   now + timedelta(days = -3)
datetime.datetime(2020, 10, 31, 22, 5, 21, 979147)

If you want to add days to a date object, the process is the same.

>>> today = datetime.date.today()

   >>>
   today
datetime.date(2020, 11, 5)

   >>>
   today + timedelta(days = 3)
datetime.date(2020, 11, 8)

Since timedelta object sets all arguments to 0 by default, we have the option to set only the ones we need. This allows us to add only minutes, for instance.

>>> now
datetime.datetime(2020, 11, 3, 22, 5, 21, 979147)

   >>>
   now + timedelta(minutes = 3)
datetime.datetime(2020, 11, 3, 22, 8, 21, 979147)

   >>>
   now + timedelta(minutes = -3)
datetime.datetime(2020, 11, 3, 22, 2, 21, 979147)

IMHO, the best way to add a certain number of years to a datetime is by using the dateutil library.

>>>
import datetime

   >>>
   from dateutil.relativedelta
import relativedelta

   >>>
   now = datetime.datetime.now()

   >>>
   now
datetime.datetime(2020, 11, 4, 22, 9, 5, 672091)

   >>>
   now + relativedelta(years = 2)
datetime.datetime(2022, 11, 4, 22, 9, 5, 672091)

Adding months to a datetime has the same problem as adding years using timedelta. This feature is not supported by default and requires manual calculation. You can use days, but you’d need to know how many days that month has and so. In a nutshell, it’s too error prone. Again, the best you can do is to use dateutil.relativedelta.

>>> from dateutil.relativedelta
import relativedelta
   >>>
   now
datetime.datetime(2020, 11, 4, 22, 9, 5, 672091)

   >>>
   now + relativedelta(years = 2)
datetime.datetime(2022, 11, 4, 22, 9, 5, 672091)

   >>>
   now + relativedelta(months = 12)
datetime.datetime(2021, 11, 4, 22, 9, 5, 672091)

   >>>
   now + relativedelta(months = 24)
datetime.datetime(2022, 11, 4, 22, 9, 5, 672091)

Suggestion : 2

There's no built-in formatter for timedelta objects, but it's pretty easy to do it yourself:

days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

Or, equivalently, if you're in Python 2.7+ or 3.2+:

seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

Now you can print it however you want:

'{} minutes, {} hours'.format(minutes, hours)

This will print:

9 minutes, 50 hours

If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:

print '{} minute{}, {} hour{}'.format(minutes, 's'
   if minutes != 1
   else '',
      hours, 's'
   if minutes != 1
   else '')

If you want to convert a timedelta into hours and minutes, you can use the total_seconds() method to get the total number of seconds and then do some math:

x = datetime.timedelta(1, 5, 41038) # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime
import timedelta
   >>>
   timedelta(seconds = 90136)
datetime.timedelta(1, 3736) >>>
   str(timedelta(seconds = 90136))
'1 day, 1:02:16'

And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:

import datetime

delta = datetime.timedelta(seconds = 10000)
time_obj = datetime.datetime.strptime(str(delta), '%H:%M:%S').time()

Something like that:

my_date = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366, tzinfo=<UTC>)
   print(my_date.strftime("%Y, %d %B"))

After edited your question to format timedelta, you could use:

def timedelta_tuple(timedelta_object):
   return timedelta_object.days, timedelta_object.seconds //3600, (timedelta_object.seconds//60)%60

I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.

def format_timedelta(td):
   hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
   hours = '0%s' % int(hours)
if minutes < 10:
   minutes = '0%s' % minutes
if seconds < 10:
   seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)

Suggestion : 3

The datetime.timedelta in the datetime module represents the difference between two dates, time, or datetime objects. For example, we have two timestamps as datetime objects,,We got the difference between two timestamps in minutes only by converting timedelta to minutes.,If you want the difference between these two timestamps, you can subtract these datetime objects. It will give a timedelta i.e.,What if we want the absolute difference in total minutes only? For that we can convert this timedelta object to minutes only. Let’s see how to do that,

The datetime.timedelta in the datetime module represents the difference between two dates, time, or datetime objects. For example, we have two timestamps as datetime objects,

from datetime
import datetime

start_timestamp = datetime(2021, 10, 1, 7, 20, 17, 100000)
end_timestamp = datetime(2021, 10, 1, 8, 25, 12, 200002)

If you want the difference between these two timestamps, you can subtract these datetime objects. It will give a timedelta i.e.

# Get different between two datetime as timedelta object.
timedelta_obj = (end_timestamp - start_timestamp)

print(timedelta_obj)
print(type(timedelta_obj))

Output:

1:04:55.100002
<class 'datetime.timedelta'>

It contains the decimal part too. If you want approx absolute value, then you can round off the minutes value i.e.

# Convert timedelta object to minutes
diff_in_minutes = timedelta_obj.total_seconds() / 60
# Round of the minutes value
diff_in_minutes = round(diff_in_minutes)

print("Total Time Difference : {} Minutes".format(diff_in_minutes))

Output

Total Time Difference: 65 Minutes

Suggestion : 4

Post date March 30, 2022 ,© 2022 The Web Dev

For instance, we write

seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

Suggestion : 5

Last Updated : 08 Sep, 2020

Output:

Difference: 36 days, 10: 04: 20
Difference in minutes: 604.3333333333334

Suggestion : 6

Timedeltas are absolute differences in times, expressed in difference units (e.g. days, hours, minutes, seconds). This method converts an argument from a recognized timedelta format / value into a Timedelta type.,Deprecated since version 1.2: Strings with units ‘M’, ‘Y’ and ‘y’ do not represent unambiguous timedelta values and will be removed in a future version,Convert argument to timedelta.,Converting numbers by specifying the unit keyword argument:

>>> pd.to_timedelta('1 days 06:05:01.00003')
Timedelta('1 days 06:05:01.000030') >>>
   pd.to_timedelta('15.5us')
Timedelta('0 days 00:00:00.000015500')
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT],
   dtype = 'timedelta64[ns]', freq = None)
>>> pd.to_timedelta(np.arange(5), unit = 's')
TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
         '0 days 00:00:03', '0 days 00:00:04'
      ],
      dtype = 'timedelta64[ns]', freq = None) >>>
   pd.to_timedelta(np.arange(5), unit = 'd')
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
   dtype = 'timedelta64[ns]', freq = None)