Categories
Python Answers

How to construct a timedelta object from a simple string with Python?

Spread the love

Sometimes, we want to construct a timedelta object from a simple string with Python.

In this article, we’ll look at how to construct a timedelta object from a simple string with Python.

How to construct a timedelta object from a simple string with Python?

To construct a timedelta object from a simple string with Python, we can use datetime’s strptime to parse the string.

For instance, we write

from datetime import datetime, timedelta

t = datetime.strptime("05:20:25","%H:%M:%S")
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)

to call strptime to parse the time string into a datetime object hours, minutes, and seconds.

Then we call timedelta with the hours, minutes, and seconds that we get from the t object to create the timedelta object.

Conclusion

To construct a timedelta object from a simple string with Python, we can use datetime’s strptime to parse the string.

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 *