Skip to main content

A flexible library to convert various time inputs into a total duration format (HH:MM:SS).

Project description

Total Time Formatter

A robust and versatile Python library to convert various time inputs into a total cumulative hours format (HH:MM:SS), where hours can exceed 24.

This tool is perfect for applications that need to calculate and display total durations, such as project time tracking, data analysis pipelines, equipment runtime logs, or simply formatting time data consistently.

Key Features

  • Versatile Inputs: Seamlessly handles a wide variety of types: str, datetime.timedelta, datetime.datetime, pandas.Timestamp, and datetime.time.
  • Total Hour Calculation: Correctly calculates total hours from inputs that include date information, allowing hour counts well beyond 24.
  • High Precision Control: Offers precise control over how fractional seconds are handled: truncate, round up, or keep the exact original precision down to the microsecond.
  • Customizable Reference Date: Allows setting a custom start date for duration calculations.
  • Pandas-Friendly: Designed to integrate perfectly with pandas DataFrames via the .apply() method.
  • Dependency-Free: Pure Python with no external dependencies required for its core logic.

Installation (from TestPyPI)

Note: This package is currently available on TestPyPI for testing purposes. To install it, you must specify the index URL:

pip install --index-url [https://test.pypi.org/simple/](https://test.pypi.org/simple/) total-time-formatter

How to Use

Import the main function and the precision mode constants to get started.

from total_time_formatter import format_total_hours, TRUNCATE, ROUND_UP, KEEP_PRECISION
from datetime import datetime, timedelta, time

1. Basic Usage with Strings

The function can intelligently parse different string formats.

# A full datetime string (calculates duration from default reference '1899-12-31')
date_str = "1900-01-02 10:30:15" 
# Expected: 1 full day (24h) + 1 day (24h) + 10h = 58 hours
print(f"Full Datetime String: {format_total_hours(date_str)}")

# A time-only string (treated as a direct duration)
duration_str = "58:30:15"
print(f"Duration String: {format_total_hours(duration_str)}")

2. Handling Different Object Types

The library automatically recognizes common Python time objects.

# A timedelta object
td_obj = timedelta(hours=75, minutes=5, seconds=22)
print(f"Timedelta Object: {format_total_hours(td_obj)}")

# A datetime object
dt_obj = datetime(1900, 1, 3, 12, 0, 0) # 3 full days + 12h = 84h
print(f"Datetime Object: {format_total_hours(dt_obj)}")

# A time object (treated as a duration from midnight)
time_obj = time(hour=5, minute=10, second=3)
print(f"Time Object: {format_total_hours(time_obj)}")

3. Controlling Precision (precision_mode)

This is a key feature for controlling how fractional seconds are handled.

time_with_ms = "10:20:30.789123"

# Truncate (default behavior)
truncated = format_total_hours(time_with_ms, precision_mode=TRUNCATE)
print(f"Truncated: {truncated}")

# Round Up
rounded = format_total_hours(time_with_ms, precision_mode=ROUND_UP)
print(f"Rounded Up: {rounded}")

# Keep Exact Precision
precise = format_total_hours(time_with_ms, precision_mode=KEEP_PRECISION)
print(f"Precise: {precise}")

4. Advanced Usage: Custom Reference Date

You can override the default reference date for duration calculations.

target_date = "2024-01-10 12:00:00"
custom_ref_date = "2024-01-01 00:00:00"

# Calculates duration from the start of 2024
# Expected: 9 days (216h) + 12h = 228 hours
duration = format_total_hours(target_date, reference_date=custom_ref_date)
print(f"Duration from custom reference: {duration}")

Integration with Pandas

The library is designed to work perfectly with pandas via .apply(), automatically handling the various data types that pandas can produce when reading data.

import pandas as pd

# Sample DataFrame simulating data read from a file
data = {
    'raw_time_data': [
        datetime(1900, 1, 2, 10, 0, 0), # A datetime object
        "75:30:15",                      # A duration string
        time(4, 15, 20),                 # A time object
        None                             # A null value
    ]
}
df = pd.DataFrame(data)

# Apply the function to create a new, clean column
df['formatted_duration'] = df['raw_time_data'].apply(format_total_hours)

print(df)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

total_time_formatter-1.0.3.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

total_time_formatter-1.0.3-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file total_time_formatter-1.0.3.tar.gz.

File metadata

  • Download URL: total_time_formatter-1.0.3.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for total_time_formatter-1.0.3.tar.gz
Algorithm Hash digest
SHA256 88624c907d0e18817e6d264548106e9088505ed61c8982bc19f1af1129ee26dd
MD5 c9803e3077c18afa0ed06ea5e901a15e
BLAKE2b-256 4338e93b78cc13e82a3b1ad44f8d60119a0be9d7f232becc43d21210d83e978e

See more details on using hashes here.

File details

Details for the file total_time_formatter-1.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for total_time_formatter-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 c71c45667a63be800b47ee4d9778c07c3eeb126809f4c822b70453db279a0ab1
MD5 e8532cc979ab061a8f28e689e5e118fe
BLAKE2b-256 e18bde8df8ea4c9c482197ff91db4fa64acda917b1f5519e3ca76711eb8b6182

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page