This is my modification(Martin, rer answers) to support weeks
attribute and return milliseconds. Some durations may use PT15.460S
fractions.
def parse_isoduration(str):
## https://mcmap.net/q/145493/-is-there-an-easy-way-to-convert-iso-8601-duration-to-timedelta
## Parse the ISO8601 duration as years,months,weeks,days, hours,minutes,seconds
## Returns: milliseconds
## Examples: "PT1H30M15.460S", "P5DT4M", "P2WT3H"
def get_isosplit(str, split):
if split in str:
n, str = str.split(split, 1)
else:
n = '0'
return n.replace(',', '.'), str # to handle like "P0,5Y"
str = str.split('P', 1)[-1] # Remove prefix
s_yr, str = get_isosplit(str, 'Y') # Step through letter dividers
s_mo, str = get_isosplit(str, 'M')
s_wk, str = get_isosplit(str, 'W')
s_dy, str = get_isosplit(str, 'D')
_, str = get_isosplit(str, 'T')
s_hr, str = get_isosplit(str, 'H')
s_mi, str = get_isosplit(str, 'M')
s_sc, str = get_isosplit(str, 'S')
n_yr = float(s_yr) * 365 # approx days for year, month, week
n_mo = float(s_mo) * 30.4
n_wk = float(s_wk) * 7
dt = datetime.timedelta(days=n_yr+n_mo+n_wk+float(s_dy), hours=float(s_hr), minutes=float(s_mi), seconds=float(s_sc))
return int(dt.total_seconds()*1000) ## int(dt.total_seconds()) | dt
datetime.timedelta
object. The standard lib doesn't have parsing for deltas, but there are packages on PyPI for you topip install
that do. If you want to know how to do it yourself, I think that's too broad for SO; you should have a go and see where (if anywhere!) you get too stuck to continue. – Cohbathdatetime.timedelta
? Is it part of a package? can you give a concrete example of what you want vs what you got? – Giant