Change Code Time Duration: from '%H:%M:%S' to 'XhYmZs' instead

Abstract: Convert H:M:S time duration strings to compact XhYmZs format in Python using datetime.timedelta.

Created: 2026-07-29 by

To convert a time duration from the standard H:M:S format to a compact XhYmZs string in Python, parse the input using datetime.timedelta, extract the hours, minutes, and seconds components, and then construct the new string by formatting these values. This approach ensures accurate handling of time arithmetic and avoids manual string splitting errors.

Understanding the Input Format

The source format typically follows the ISO 8601 duration or standard clock notation, such as 01:30:45. In many scripting scenarios, this string represents a total elapsed time rather than a specific time of day. When working with Linux systems and Bash scripts that call Python utilities, it is crucial to distinguish between parsing a timestamp for display and calculating a duration for logic. The goal is to transform the colon-separated numeric strings into a human-readable, condensed format where each unit is explicitly labeled with its suffix. For instance, an input of 10:05:03 should become 10h5m3s. Note that leading zeros in minutes or seconds (like 05) are often preserved or stripped depending on preference, but the standard interpretation usually treats them as integer values. If the input contains fractional seconds, they must be handled separately or truncated depending on the precision requirements of your application.

Python Implementation Strategy

The most robust method involves using the built-in datetime module. Specifically, datetime.timedelta is designed to store durations, making it ideal for this conversion. You can create a timedelta object directly from the string representation if it matches the expected pattern, or you can split the string manually to construct the object. Here is the recommended code structure:
from datetime import timedelta

def format_duration(duration_str):
    # Parse the H:M:S string into a timedelta object
    parts = duration_str.split(':')
    
    # Handle cases where only M:S is provided
    if len(parts) == 2:
        h, m, s = 0, int(parts[0]), int(parts[1])
    else:
        h, m, s = int(parts[0]), int(parts[1]), int(parts[2])
        
    td = timedelta(hours=h, minutes=m, seconds=s)
    
    # Extract components
    total_seconds = int(td.total_seconds())
    hours, remainder = divmod(total_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    
    # Format to XhYmZs
    return f"{hours}h{minutes}m{seconds}s"

print(format_duration("01:30:45")) # Output: 1h30m45s
This script splits the input string by the colon delimiter. It assigns the first part to hours, the second to minutes, and the third to seconds. By converting these integers into a timedelta object, we ensure that any edge cases involving zero values are handled correctly. Finally, the divmod function is used to cleanly separate the total seconds back into hours, minutes, and seconds for the final output string.

Handling Edge Cases in Scripts

When integrating this Python logic into larger Bash workflows, consider how invalid inputs are managed. If the input string is malformed, such as AB:CD:EF, the int() conversion will raise a ValueError. It is best practice to wrap the parsing logic in a try-except block to catch these exceptions and return a default value or an error message. Additionally, some systems may provide durations with more than two digits for hours, such as 100:00:00. The above script handles this naturally because timedelta supports large hour values. However, if you need to normalize the output so that minutes never exceed 59, the divmod logic already performs this normalization automatically. For example, 01:65:00 (one hour, sixty-five minutes) would be normalized to 2h5m0s. For more insights on managing script outputs across different environments, see Determining Script Execution on Windows, Linux, and MacOS. This is particularly relevant if your toolchain needs to behave consistently regardless of the operating system hosting the Python interpreter.

Optimizing for Performance

If you are processing thousands of duration strings in a tight loop, creating a timedelta object for each one might introduce overhead. In such high-performance scenarios, you can bypass the datetime module entirely. A direct string manipulation approach using f-strings is faster and requires fewer imports.
def fast_format(duration_str):
    try:
        h, m, s = duration_str.split(':')
        return f"{int(h)}h{int(m)}m{int(s)}s"
    except ValueError:
        return "Invalid Format"
This version assumes the input is always valid and strictly formatted as three colon-separated integers. It converts each part to an integer to strip leading zeros (e.g., 05 becomes 5) and then concatenates them with the suffixes. While less robust against malformed input, it is significantly lighter on resources.

Integration with Bash Workflows

Often, this conversion is required within a Bash script that processes logs or monitoring data. You can embed the Python code directly into the Bash script using a heredoc or by calling a one-liner. Using a dedicated Python function allows you to keep the logic clean and maintainable, avoiding complex Bash arithmetic which can be prone to syntax errors when dealing with variable expansion. For further reading on troubleshooting common issues in Bash scripting, refer to Bash Scripts Not Providing Expected Output?. Ensuring that your Python calls return consistent exit codes and formatted strings will help diagnose why a downstream command might fail to parse the time duration correctly.

Frequently Asked Questions

How do I handle fractional seconds in the input?

If your input includes milliseconds, such as 01:30:45.500, you must modify the parsing logic to split on both colons and dots. Extract the integer seconds and the fractional part separately, then append the milliseconds to the final string or round them off based on your precision needs.

What if the input only has minutes and seconds (M:S)?

The robust script provided earlier checks the length of the split list. If only two parts are present, it assumes the first is minutes and the second is seconds, setting hours to zero. This prevents index out-of-range errors and correctly formats the output as 0hXmYs.

Can I use this method for negative durations?

The standard timedelta approach does not natively support negative signs in the string parsing without modification. To handle negative durations, check for a leading minus sign, parse the absolute values, and prepend a '-' character to the final formatted string.

Why is my output showing '0h' instead of omitting it?

The current implementation always includes all three components (XhYmZs). If you want to omit zero-value components (e.g., showing just 30m45s), you would need to add conditional logic to check if each component is greater than zero before appending it to the result string.

Is there a way to do this without Python?

Yes, you can achieve similar results using pure Bash with parameter expansion and arithmetic evaluation, though it is more verbose and harder to read. Alternatively, tools like awk can parse and reformat the string efficiently in a single pass during log processing.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More