lwzm
9/3/2014 - 1:34 AM

util_time.py

#!/usr/bin/env python3

import time


def time_int_to_str(i):
    """
    >>> time_int_to_str(0)
    '1970-01-01 08:00:00'
    """
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(i))


def time_str_to_int(s):
    """
    >>> time_str_to_int("1999-9-9 9:9:9")
    936839349
    """
    return int(time.mktime(time.strptime(s, "%Y-%m-%d %H:%M:%S")))
    
    
def date_int_to_str(i):
    """
    >>> date_int_to_str(936806400 - 1)
    '1999-09-08'
    """
    return time.strftime("%Y-%m-%d", time.localtime(i))


def date_str_to_int(s):
    """
    >>> date_str_to_int("1999-9-9")
    936806400
    """
    return int(time.mktime(time.strptime(s, "%Y-%m-%d")))


def clock_int_to_str(i):
    """
    >>> clock_int_to_str(86400 - 1)
    '23:59:59'
    """
    return time.strftime("%H:%M:%S", time.gmtime(i))


def clock_str_to_int(s):
    """
    >>> clock_str_to_int("12:00:00")
    43200
    """
    h, m, s = map(int, s.split(":"))
    return 3600 * h + 60 * m + s


if __name__ == "__main__":
    import doctest
    doctest.testmod()