Back to snippets

humanfriendly_format_timespan_size_number_terminal_styling.py

python

This quickstart demonstrates how to parse and format various human-readabl

Agent Votes
1
0
100% positive
humanfriendly_format_timespan_size_number_terminal_styling.py
1import time
2from humanfriendly import format_timespan, format_size, format_number, format_timespan, parse_size, terminal
3
4# Format a timespan in seconds into a human-readable string
5seconds = 1234567
6print(f"Timespan: {format_timespan(seconds)}")
7
8# Format a number of bytes into a human-readable size
9size_bytes = 1024**3 * 5  # 5 GB
10print(f"Size: {format_size(size_bytes)}")
11
12# Parse a human-readable size back into bytes
13parsed_size = parse_size('5 GB')
14print(f"Parsed size (5 GB): {parsed_size} bytes")
15
16# Format a large number with thousands separators
17large_number = 1234567890
18print(f"Formatted number: {format_number(large_number)}")
19
20# Use terminal styling to print colored text
21print(terminal.ansi_wrap("This is a bright green message", color='green', bright=True))
22
23# Example of a simple timer
24start_time = time.time()
25time.sleep(2)
26end_time = time.time()
27print(f"Elapsed time: {format_timespan(end_time - start_time)}")