Skip to content

Instantly share code, notes, and snippets.

@moreati
Created February 26, 2022 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moreati/d90cd36d5e94781feeec8d9e23510b6e to your computer and use it in GitHub Desktop.
Save moreati/d90cd36d5e94781feeec8d9e23510b6e to your computer and use it in GitHub Desktop.
Prototype of datetime.timedelta.__format__() method
import datetime
import re
class timedelta(datetime.timedelta):
def __format__(value, format_spec):
if not format_spec:
return str(value)
pattern = re.compile(r'%([WdDhHmMsSuUT%])')
def replace(match):
specifier = match.group(1)
return {
'W': str(value // datetime.timedelta(weeks=1)),
'd': str(value.days % 7),
'D': str(value // datetime.timedelta(days=1)),
'h': str(value.seconds // 3600),
'H': str(value // datetime.timedelta(hours=1)),
'm': str((value.seconds % 3600) // 60),
'M': str(value // datetime.timedelta(minutes=1)),
's': str(((value.seconds % 3600) % 60)),
'S': str(value // datetime.timedelta(seconds=1)),
'u': str(value.microseconds),
'U': str(value // datetime.timedelta(microseconds=1)),
'T': str(value.total_seconds()),
'%': '%',
}[specifier]
return pattern.sub(replace, format_spec)
if __name__ == '__main__':
duration = timedelta(weeks=1, days=2, hours=3, minutes=4, seconds=5, milliseconds=6, microseconds=7)
print(f'{duration:%W wk %d day %h hr %m min %s s %u µs}')
@moreati
Copy link
Author

moreati commented Feb 26, 2022

$ python3 ~/src/timedelta_format.py
1 wk 2 day 3 hr 4 min 5 s 6007 µs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment