Constructing Timedelta Objects from Simple Strings
When creating a function that requires parsing strings into timedelta objects, you may encounter various input formats such as "32m", "2h32m", "4:13", or "5hr34m56s". To streamline this task, consider leveraging the powerful capabilities of Python's datetime module and its strptime method.
Using datetime.strptime
The elegant solution is to utilize the strptime method to parse the input string based on a specified format:
<code class="python">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)</code>
Breakdown:
Once the timedelta object is constructed, you can utilize it normally, such as:
<code class="python">print(delta) assert(5*60*60+20*60+25 == delta.total_seconds())</code>
By harnessing the capabilities of datetime.strptime, you can efficiently parse strings of various formats into timedelta objects, simplifying your function's implementation.
The above is the detailed content of How to Create Timedelta Objects from Textual Strings?. For more information, please follow other related articles on the PHP Chinese website!