Home  >  Article  >  Backend Development  >  How to Convert String Time Durations to timedelta Objects in Python?

How to Convert String Time Durations to timedelta Objects in Python?

DDD
DDDOriginal
2024-10-22 16:56:02216browse

How to Convert String Time Durations to timedelta Objects in Python?

Parsing Strings to Timedelta Objects

In the realm of Python programming, it's often necessary to convert string inputs representing time durations into timedelta objects. For instance, a user may enter values like "32m", "4:13", or "5hr34m56s."

Elegant Solution using strptime

A highly effective and elegant approach to tackle this challenge is to leverage the strptime method of the datetime module. This powerful method allows for flexible string parsing, enabling the creation of timedelta objects from a wide range of string formats.

<code class="python">from datetime import datetime, timedelta
# Input string in "HH:MM:SS" format
t = datetime.strptime("05:20:25","%H:%M:%S")
# Extract hour, minute, and second from datetime object
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
print(delta)  # Output: 5:20:25</code>

The above is the detailed content of How to Convert String Time Durations to timedelta Objects in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn