Source

quechua / scripts / time_converter.py

Full commit
#!/usr/bin/env python

import time

from datetime import datetime
from datetime import timedelta

TIME_SUFFIXES = ('s','m','h','D')


# datetime.total_seconds() only from Python 2.7
def total_seconds(td):
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 

def convert_to_seconds(input_date):
    """
    This function tries to convert date custom format into seconds
    Example:
    - 24H -> 86400 seconds
    - 1D  -> 86400 seconds
    - 12H -> 43200 seconds
    - 60m -> 3600  seconds
    - 1M  -> 1D * 31
    """
    def get_multiplier(measure):
        if measure == 's':
            return 1
        elif measure == 'm':
            return 60
        elif measure == 'h':
            return 60*60
        elif measure == 'D':
            return 60*60*24
        else:
            return 1

    
    if not input_date:
        return (3600,"Empty input,defaults to 3600 seconds")


    result_log=''
    input_date = input_date.strip()
    time_measure = input_date[-1] # get last elem
    if time_measure not in TIME_SUFFIXES:
        time_measure = 's'
    multiplier = get_multiplier(time_measure)
    try:
        date = int(input_date[:-1]) * multiplier
        return (date,result_log)
    except ValueError:
        result_log =  "Bad input format, defaults to 1 hour (3600 seconds)"
        return (3600,result_log)

def convert_dates_ranges_to_seconds(time_from, time_to,date_format='%Y-%m-%d %H:%M:%S'):
    time_from = datetime.strptime(time_from,date_format)
    time_to = datetime.strptime(time_to,date_format)
    delta = time_to - time_from
    print "Total seconds: %d" % int(total_seconds(delta))
    return int(total_seconds(delta))

def calculate_ranges_from_interval(input_date):
    """
    The functions calculates (from,to) date ranges
    """
    SQL_FORMAT ="YYYY-MM-DD HH24:MI:SS"

    if not input_date:
        return (3600,"Empty input,defaults to 3600 seconds") 

    date = datetime.today()
    input_date = input_date.strip()

    time_measure = input_date[-1]
    try:
        if time_measure not in TIME_SUFFIXES:
            raise ValueError
        interval   = int(input_date[:-1])
    except ValueError:
        time_measure = 's'
        interval = 3600

    to_date = None
    delta = timedelta(seconds=0)
    if time_measure == 's':
        to_date = date
        delta = timedelta(seconds=interval)
        from_date = to_date - delta
    elif time_measure == 'm':
        to_date = datetime(year=date.year, month=date.month, day=date.day, hour=date.hour, minute=date.minute,second=0)
        delta = timedelta(minutes=interval)
        from_date = to_date - delta
    elif time_measure == 'h':
        to_date = datetime(year=date.year, month=date.month, day=date.day, hour=date.hour)
        delta = timedelta(hours=interval)
        from_date = to_date - delta
    elif time_measure == 'D':
        to_date =  datetime(year=date.year, month=date.month, day=date.day)
        delta = timedelta(days=interval)
        from_date= to_date - delta
#    elif time_measure == 'M':
#        to_date = datetime(year=date.year, month=date.month,day=1)
#        from_date = to_date - timedelta(days=interval*DAYS_IN_MONTH)
#    elif time_measure == 'Y':
#        to_date = datetime(year=date.year,month=1,day=1)
#        from_date = to_date - timedelta(days=interval*DAYS_IN_Y)

    to_str   = "to_timestamp('%s','%s')" % ( to_date.strftime("%Y-%m-%d %H:%M:%S"), SQL_FORMAT)
    from_str = "to_timestamp('%s','%s')" % ( from_date.strftime("%Y-%m-%d %H:%M:%S"), SQL_FORMAT)
    
    return (from_str, to_str,total_seconds(delta))

def validate_dateformat(inp,date_format='%Y-%m-%d %H:%M:%S'):
    """
    Validates whether input is in provided format.
    Returns a tuple with boolean value and log (empty if successful)
    """
    try:
        stime = time.strptime(inp, date_format)
    except ValueError,e:
        return (False,str(e))
    return (True,'')


def sqlize_date_string(inp):
    """
    Formats string so it can be used directly as a date in PostgreSQL (or maybe more databases)
    databases.
    """
    DATE_FORMAT='%Y-%m-%d %H:%M:%S'
    SQL_FORMAT ="YYYY-MM-DD HH24:MI:SS"
    try:
        stime = time.strptime(inp,DATE_FORMAT)
    except ValueError,e:
        print str(e)
        return 'CURRENT_TIMESTAMP'

    datetime_obj = datetime.fromtimestamp(time.mktime(stime))
    formated_date = "to_timestamp('%s','%s')" % (datetime_obj.strftime(DATE_FORMAT), SQL_FORMAT )
    return formated_date


#print convert_to_seconds("")
#f,t= calculate_time_ranges("2D")
#print f,t