Categories
Python Answers

How to convert datetime.timedelta to minutes, hours in Python?

Spread the love

Sometimes, we want to convert datetime.timedelta to minutes, hours in Python.

In this article, we’ll look at how to convert datetime.timedelta to minutes, hours in Python.

How to convert datetime.timedelta to minutes, hours in Python?

To convert datetime.timedelta to minutes, hours in Python, we can use the timedelta’s total_seconds method to get the datetime difference in seconds.

For instance, we write

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

to call total_seconds on the duration timedelta object.

And then we get the hours, minutes, and seconds by calculating the values from the seconds.

Conclusion

To convert datetime.timedelta to minutes, hours in Python, we can use the timedelta’s total_seconds method to get the datetime difference in seconds.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *