degal/format.py
author Tero Marttila <terom@fixme.fi>
Fri, 05 Jun 2009 19:29:04 +0300
changeset 56 80658a2eebf6
child 77 2a53c5ade434
permissions -rw-r--r--
add format.py module with filesize/filetime, replaces helpers.py and formatbytes
"""
    Miscellaneous formatting functions
"""

import datetime

def filesize (bytes) :
    """
        Returns a human-readable string describing the given filesize

        The returned string is either "x.xx MiB", "x.xx KiB", or "zzz Bytes", whereby x.xx is at least 0.1
    """

    kb, bytes   = divmod(bytes, 1024)
    mb, kb      = divmod(kb, 1024)

    if mb or kb > 1024 / 10.0 :
        return "%f.2 MiB" % (mb + kb / 1024 + bytes / 1024**2)

    elif kb or bytes > 1024 / 10.0 :
        return "%f.2 KiB" % (kb + bytes / 1024)

    else :
        return "%d Bytes" % bytes

def filetime (ts) :
    """
        Returns a human-readable string describing the given file timestamp
    """

    return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")