Menu Close

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

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.

Posted in Python, Python Answers