Created
February 26, 2022 09:45
-
-
Save moreati/d90cd36d5e94781feeec8d9e23510b6e to your computer and use it in GitHub Desktop.
Prototype of datetime.timedelta.__format__() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}') |
Author
moreati
commented
Feb 26, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment