Dup Ver Goto 📝

ToFromHmsTime

PT2/lang/python/misc python hms time does not exist
To
60 lines, 183 words, 1317 chars Page 'ToFromHmsTime' does not exist.

A convention I use for writing time durations without needing symbols like colons, good for filenames for example, is 4h34m5s where the trailing s is optional, so 4h3 is the same as 4h3s.

Here are a couple of simple convenience functions that convert between this and an integral number of seconds.

import re

def to_dhms_from_int(x):
  d, h = divmod(x,24*3600)
  h, x = divmod(x,3600)
  m, s = divmod(x,60)
  return d,h,m,s

def from_dhms_to_int(d=0,h=0,m=0,s=0):
  return s + 60*(m + 60*( h + 24*d ))

def to_hmsstr_from_dhms(d=0,h=0,m=0,s=0):
  t = ""
  if d > 0:
    t += f"{d}d"
  if h > 0:
    t += f"{h:02d}h"
  if m > 0:
    t += f"{m:02d}m"
  if s > 0:
    t += f"{s:02d}s"
  t = t.lstrip("0")
  return t

def from_hmsstr_to_dhms(x):
  match = re.match(r"(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$",x)
  if not match:
    raise ValueError(f"Not valid dhms: '{x}'")
  dhms = [ int(y) if y is not None else 0 for y in match.groups() ]
  return dhms

def dhms(x):
  return from_dhms_to_int(*from_hmsstr_to_dhms(x))

def todhms(x):
  return to_hmsstr_from_dhms(*to_dhms_from_int(x))

tests = [
  "4d7h2m3s",
  "4d7h2m3",
  "5m3s",
  "5m3",
  "4h3s",
  "4h2",
  "4h2m3s",
  "4h2m3",
  "43",
]

for x in tests:
  print(f"{x}: {from_hmsstr_to_dhms(x)} -- {dhms(x)} == {todhms(dhms(x))}")