# quechua / scripts / time_converter.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145``` ```#!/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 ```