Python datetime delta minutes

Convert timedelta to minutes in Python

This article will discuss how we can convert the datetime module’s timedelta object to total minutes.

A little background of the problem in hand,

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) )

This timedelta object contains the time difference between two datetimes. But when we printed it, the absolute difference gets printed in hh:mm::ss.ffffff format.

Frequently Asked:

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,

Читайте также:  Php curl peer certificate

Convert timedelta to minutes in python

The timedelta object represents a duration. It has a function total_seconds(), which gives the total seconds in the complete duration of timedelta object. We can get the whole seconds from it and then divide it by 60 to get the entire duration in minutes only. For example,

# Convert timedelta object to minutes diff_in_minutes = timedelta_obj.total_seconds() / 60 print("Total Time Difference : <> Minutes".format(diff_in_minutes) )
Total Time Difference : 64.91833336666667 Minutes

We got the difference between two timestamps in minutes only by converting timedelta to minutes.

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) )
Total Time Difference : 65 Minutes

The complete working example is as follows,

from datetime import datetime start_timestamp = datetime(2021, 10, 1, 7, 20, 17, 100000) end_timestamp = datetime(2021, 10, 1, 8, 25, 12, 200002) # Get different between two datetime as timedelta object. timedelta_obj = (end_timestamp - start_timestamp) print(timedelta_obj) print( type(timedelta_obj) ) # Convert timedelta object to minutes diff_in_minutes = timedelta_obj.total_seconds() / 60 print("Total Time Difference : <> Minutes".format(diff_in_minutes) ) # Round of the minutes value diff_in_minutes = round(diff_in_minutes) print("Total Time Difference : <> Minutes".format(diff_in_minutes) )
1:04:55.100002 Total Time Difference : 64.91833336666667 Minutes Total Time Difference : 65 Minutes

Today we learned that how we can convert datetime.timedelta to minutes in python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Python datetime delta minutes

Last updated: Feb 19, 2023
Reading time · 4 min

banner

# Add minutes to datetime in Python

Use the timedelta() class from the datetime module to add minutes to datetime, e.g. result = dt + timedelta(minutes=10) .

The timedelta class can be passed a minutes argument and adds the specified number of minutes to the datetime object.

Copied!
from datetime import datetime, timedelta d = '2023-11-24 09:30:00.000123' # 👇️ convert string to datetime object dt = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f') print(dt) # 👉️ 2023-11-24 09:30:00.000123 result = dt + timedelta(minutes=29) print(result) # 👉️ 2023-11-24 09:59:00.000123

add minutes to datetime

Make sure to import the datetime and timedelta classes from the datetime module.

The example creates a datetime object from a datetime string and adds minutes to it.

Copied!
from datetime import datetime, timedelta d = '2023-11-24 09:30:00.000123' # 👇️ convert string to datetime object dt = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f') print(dt) # 👉️ 2023-11-24 09:30:00.000123 result = dt + timedelta(minutes=29) print(result) # 👉️ 2023-11-24 09:59:00.000123

The datetime.strptime() method returns a datetime object that corresponds to the provided date string, parsed according to the format.

If you have a date string that is formatted in a different way, use this table of the docs to look up the format codes you should pass as the second argument to the strptime() method.

# Add minutes to a datetime object using the timedelta class

The following example uses the datetime class to create a datetime object and the timedelta class to add minutes to it.

Copied!
from datetime import datetime, timedelta dt = datetime(2023, 9, 24, 9, 30, 35) print(dt) # 👉️ 2023-09-24 09:30:35 result = dt + timedelta(minutes=15) print(result) # 👉️ 2023-09-24 09:45:35

add minutes to datetime object using timedelta class

We passed values for the year , month , day , hour , minute and second arguments.

# Adding minutes to the current time

You can use the datetime.today() method to get a datetime object that represents the current date and time to add minutes to the current time.

Copied!
from datetime import datetime, timedelta now = datetime.today() print(now) # 👉️ 2023-02-19 05:32:39.521250 result = now + timedelta(minutes=5) print(result) # 👉️ 2023-02-19 05:37:39.521250

add minutes to current time

The datetime.today() method returns the current local datetime .

The timedelta class can be passed the days , weeks , hours , minutes , seconds , milliseconds and microseconds as arguments.

All of the arguments are optional and default to 0 .

It’s best to only use keyword arguments in a call to the timedelta class as the order of arguments can be confusing.

We only provided a value for the minutes argument in the example.

We need to use a datetime object because it automatically rolls over the hours, days, months and years if necessary.

This wouldn’t be possible if we only had the time component. For example, 11:59:30PM + 15 minutes would raise an exception.

# Using the time() method to extract the time after the operation

If you only need to extract the time after the operation, call the time() method on the datetime object.

Copied!
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2023-02-19 05:33:06.313209 result = now + timedelta(minutes=25) print(result) # 👉️ 2023-02-19 05:58:06.313209 # ✅ only get updated time print(result.time()) # 👉️ 05:58:06.313209

extract time after operation

We used the datetime.now method to get the current local date and time.

The datetime.time method returns a time object with the same hour, minute, second and millisecond.

If you need to get the time formatted as HH:MM:SS , use a formatted string literal.

Copied!
from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2023-02-19 05:33:54.666803 result = now + timedelta(minutes=25) print(result) # 👉️ 2023-02-19 05:58:54.666803 print(result.time()) # 👉️ 05:58:54.666803 # 👇️ format as HH:MM:SS print(f'result:%H:%M:%S>') # 👉️ 05:58:54

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Make sure to wrap expressions in curly braces — .

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

# Use datetime.combine if you only have the time component

If you only have the time component, use the datetime.combine method to combine the time with the current (or some other) date and get a datetime object.

Copied!
from datetime import datetime, date, timedelta, time t = time(9, 25) print(t) # 👉️ 09:25:00 result = datetime.combine(date.today(), t) + timedelta(minutes=30) print(result) # 👉️ 2023-02-19 09:55:00 only_t = result.time() print(only_t) # 👉️ 09:55:00

The datetime.combine method takes a date and time as arguments and returns a new datetime object by combining them.

Once we get a datetime object, we can use the timedelta class to add minutes to it.

Use the time() method on the datetime object if you only need to extract the time after the operation.

Copied!
from datetime import datetime, date, timedelta, time t = time(9, 25) print(t) # 👉️ 09:25:00 result = datetime.combine(date.today(), t) + timedelta(minutes=30) print(result) # 👉️ 2023-02-19 09:55:00 # ✅ only get updated time only_t = result.time() print(only_t) # 👉️ 09:55:00

The datetime.time method returns a time object with the same hour, minute, second and millisecond.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Convert timedelta to Minutes in Python (Example)

TikTok Icon Statistics Globe

In this tutorial, you’ll learn how to convert a timedelta object to minutes in the Python programming language.

The tutorial consists of an example illustrating the conversion of timedelta objects into minutes. To be more precise, the article contains the following:

Example Data & Imported Modules

import datetime # Loading datetime module

Now we should construct some data that we can use in the exemplifying code later on:

td = datetime.timedelta(days=71, seconds=34512, microseconds=150475) # timedelta construction print(td) # printing timedelta # 71 days, 9:35:12.150475

Example: Calculate the Equivalent Time in Days

To convert our timedelta object called td to seconds, we will use the total_seconds() function as given below.

total_seconds = td.total_seconds() # converting timedelta to seconds

Then we will divide the result by 60 to change the unit from seconds to minutes.

td_in_minutes = total_seconds / 60 # converting the second count to minutes print(td_in_minutes) # printing result in minutes # 102815.20250791666

Video, Further Resources & Summary

In case you need further information on the examples of this article, I recommend having a look at the following video on my YouTube channel. In the video, I’m explaining the Python programming syntax of this page:

The YouTube video will be added soon.

In addition, you may want to read the related posts on Statistics Globe.

To summarize: In this article, you have learned how to express the timedelta object in minutes in the Python programming language. Please let me know in the comments section, in case you have any additional comments and/or questions.

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.

Источник

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