Is there a simple way to convert a string into a timedelta type in python?
Is there not much demand for this?
The method of changing the timedelta type to string was scattered on the web.
The string is data such as 01:23:15 .Data such as 1 hour 23 minutes 15 seconds
When I thought about the same thing before, I thought I could do this while looking at Python's manual. I made the following code.I use the subtraction of datetime to be timedelta
from datetime import datetime, timedelta
stamp = '01:23:15'
t=datetime.strptime('2019-01-01'+stamp,'%Y-%m-%d%H:%M:%S') -datetime(2019,1,1)
print(type(t),t)
<class'datetime.timedelta'>1:23:15
This is a method of converting using only standard libraries.This method parses :
as a separator.
import datetime
data="01:23:15"
hours, minutes, seconds = map(int, data.split(":"))
td = datetime.timedelta (hours=hours, minutes=minutes, seconds=seconds)
print(type(td),td)
© 2024 OneMinuteCode. All rights reserved.