def date_to_seconds(date_str): # A function that converts our preferred date format to seconds since the # epoch. # First, we need to munch on our date_str to get the information we need. timezone, date_rem = gstr.munch(date_str, "#() ") year, date_rem = gstr.munch(date_rem,"/") month, date_rem = gstr.munch(date_rem,"/") day, date_rem = gstr.munch(date_rem," ") hour, date_rem = gstr.munch(date_rem,":") minute, date_rem = gstr.munch(date_rem,":") second, date_rem = gstr.munch(date_rem,".") # Convert to integers. year = int(year) ; month = int(month) ; day = int(day) hour = int(hour) ; minute = int(minute) ; second = int(second) # We need to determine the day of the week and of the year, which we can do # quickly with datetime. date_tuple[6] and [7] contain those data. date_tuple = datetime.date(year,month,day).timetuple() # Now we use that, along with our previously known values, to create the # full time tuple. The final -1 means we don't know the DST status, so # Python will figure it out for us. time_tuple = (date_tuple[0], date_tuple[1], date_tuple[2], hour, minute, second, date_tuple[6], date_tuple[7], -1) # Now getting the epoch seconds is easy. seconds = time.mktime(time_tuple) return seconds
def std_to_sql_date(std_date): # This function converts a date string in our preferred format into a SQL # format. # # STD: 2014/07/03 13:22:13 # SQL: 2014-07-03-13.22.13.000000 # Some munching will extract the relevant numbers so we can place them # into a different string. year, std_rem = gstr.munch(std_date, "/ ") month, std_rem = gstr.munch(std_rem, "/") day, std_rem = gstr.munch(std_rem, " ") hour, std_rem = gstr.munch(std_rem, ":") minute, std_rem = gstr.munch(std_rem, ":") second, std_rem = gstr.munch(std_rem, ". \n\t\r") sql_date = "%s-%s-%s-%s.%s.%s.000000" % (year, month, day, hour, minute, second) return sql_date
def sql_date_to_std(sql_date): # This function converts a SQL-formatted date string into our preferred # format. # # SQL: 2014-07-03-13.22.13.000000 # STD: 2014/07/03 13:22:13 # Some munching will extract the relevant numbers so we can place them # into a different string. year, sql_rem = gstr.munch(sql_date, "- ") month, sql_rem = gstr.munch(sql_rem, "-") day, sql_rem = gstr.munch(sql_rem, "-") hour, sql_rem = gstr.munch(sql_rem, ".") minute, sql_rem = gstr.munch(sql_rem, ".") second, sql_rem = gstr.munch(sql_rem, ". \n\t\r") std_date = "%s/%s/%s %s:%s:%s" % (year, month, day, hour, minute, second) return std_date