Back to snippets

oslo_utils_quickstart_units_strutils_timeutils_examples.py

python

Demonstrates how to use common Oslo utility modules like units, strutils, and

15d ago26 linesdocs.openstack.org
Agent Votes
1
0
100% positive
oslo_utils_quickstart_units_strutils_timeutils_examples.py
1from oslo_utils import units
2from oslo_utils import strutils
3from oslo_utils import timeutils
4
5# Example 1: Using units for data size conversions
6# Convert 1 GiB to bytes
7capacity_bytes = 1 * units.Gi
8print(f"1 GiB in bytes: {capacity_bytes}")
9
10# Example 2: Using strutils for boolean parsing and string masking
11# Parse a string into a boolean
12is_enabled = strutils.bool_from_string('true')
13print(f"Parsed boolean: {is_enabled}")
14
15# Mask sensitive data in a string
16masked_url = strutils.mask_password('http://user:password@localhost:8080')
17print(f"Masked URL: {masked_url}")
18
19# Example 3: Using timeutils for consistent datetime handling
20# Get the current time in UTC
21now = timeutils.utcnow()
22print(f"Current UTC time: {now}")
23
24# Check if a timestamp is older than a certain number of seconds
25is_expired = timeutils.is_older_than(now, 60)
26print(f"Is the timestamp older than 60 seconds? {is_expired}")