Source code for core.utils.time

# core/utils.py
#
#

""" utils package. """

__copyright__ = "Copyright 2015, B.H.J Thate"

## IMPORT

import calendar
import datetime
import time
import os
import re

## DEFINEs

timere = re.compile('(\S+)\s+(\S+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)')
bdmonths = ['Bo', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
monthint = {
            'Jan': 1,
            'Feb': 2,
            'Mar': 3,
            'Apr': 4,
            'May': 5,
            'Jun': 6,
            'Jul': 7,
            'Aug': 8,
            'Sep': 9,
            'Oct': 10,
            'Nov': 11,
            'Dec': 12 
           }

## TIME

[docs]def fn_time(daystr): daystr = daystr.replace("_", ":") datestr = " ".join(daystr.split(os.sep)[-2:]) try: return time.mktime(time.strptime(datestr, "%Y-%m-%d %H:%M:%S")) except: return 0
[docs]def dtime(stamp): return datetime.datetime.fromtimestamp(stamp)
[docs]def ptime(daystr): return datetime.datetime.strptime(daystr, '%Y-%m-%d')
[docs]def tdiff(d1, d2): return datetime.timedelta(d1, d2)
[docs]def rtime(): return str(datetime.datetime.now()).replace(" ", os.sep).replace(":", "_")
[docs]def ftime(datestr): return str(datestr.replace(" ", os.sep).replace(":", "_"))
[docs]def hms(): return str(datetime.datetime.today()).split()[1].split(".")[0]
[docs]def day(): return str(datetime.datetime.today()).split()[0]
[docs]def time_string(*args, **kwargs): timestamp = args[0] result = None try: result = str(datetime.datetime.fromtimestamp(timestamp)) except: error() return result
[docs]def time_time(*args, **kwargs): stamp = args[0] time_str = time_string(stamp) return time_str
[docs]def make_time(daystr): daystr = daystr.replace("_", ":") return time.mktime(time.strptime(daystr, "%a %b %d %H:%M:%S %Y"))
[docs]def to_day(daystr): return time.mktime(time.strptime(daystr, "%Y-%m-%d"))
[docs]def to_time(daystr): return time.mktime(time.strptime(daystr, "%H:%M:%S"))
[docs]def b_time(daystr): if "saved" in obj: return a_time(obj.saved) return 0.0
[docs]def a_time(daystr): daystr = daystr.replace("_", ":") return time.mktime(time.strptime(daystr, "%Y-%m-%d %H:%M:%S"))
[docs]def short_date(*args, **kwargs): # Mon, 25 Oct 2010 18:05:33 -0700 (PDT) # ['13', 'Oct', '2012', '20:43:46', '+0300'] date = args[0] if not date: return None date = date.replace("_", ":") res = date.split() ddd = "" try: if "+" in res[3]: raise ValueError if "-" in res[3]: raise ValueError int(res[3]) ddd = "{:4}-{:#02}-{:#02} {:6}".format(res[3], monthint[res[2]], int(res[1]), res[4]) except (IndexError, KeyError, ValueError): try: if "+" in res[4]: raise ValueError if "-" in res[4]: raise ValueError int(res[4]) ddd = "{:4}-{:#02}-{:02} {:6}".format(res[4], monthint[res[1]], int(res[2]), res[3]) except (IndexError, KeyError, ValueError): try: ddd = "{:4}-{:#02}-{:02} {:6}".format(res[2], monthint[res[1]], int(res[0]), res[3]) except (IndexError, KeyError): try: ddd = "{:4}-{:#02}-{:02}".format(res[2], monthint[res[1]], int(res[0])) except (IndexError, KeyError): ddd = "" return ddd.replace(":", "_")
[docs]def short_time(*args, **kwargs): date = args[0] if not date: return None date = date.replace("_", ":") res = date.split() ddd = "" try: if "+" in res[3]: raise ValueError if "-" in res[3]: raise ValueError int(res[3]) ddd = "{:6}".format(res[4]) except (IndexError, KeyError, ValueError): try: if "+" in res[4]: raise ValueError if "-" in res[4]: raise ValueError int(res[4]) ddd = "{:6}".format(res[3]) except (IndexError, KeyError, ValueError): try: ddd = "{:6}".format(res[3]) except (IndexError, KeyError): pass return ddd.replace(":", "_")
[docs]def nr_days(seconds): return int(seconds/(60*60*24))
[docs]def elapsed(seconds): txt = "" nsec = int(float(seconds)) year = 365*24*60*60 week = 7*24*60*60 day = 24*60*60 hour = 60*60 minute = 60 #nsec -= nsec * leapfactor years = int(nsec/year) nsec -= years*year weeks = int(nsec/week) nsec -= weeks*week days = int(nsec/day) nsec -= days*day hours = int(nsec/hour) nsec -= hours*hour minutes = int(nsec/minute) sec = nsec - minutes*minute txt += "%sy" % years txt += "%sw" % weeks txt += "%sd" % days txt += " %sh" % hours txt += "%sm" % minutes txt += "%ss" % int(sec) if txt: return txt else: return "0s"
[docs]def elapsed_days(seconds): txt = "" nsec = int(float(seconds)) year = 365*24*60*60 week = 7*24*60*60 day = 24*60*60 hour = 60*60 minute = 60 #nsec -= nsec * leapfactor years = int(nsec/year) nsec -= years*year weeks = int(nsec/week) nsec -= weeks*week days = int(nsec/day) nsec -= days*day hours = int(nsec/hour) nsec -= hours*hour minutes = int(nsec/minute) sec = nsec - minutes*minute if years: txt += "%sy" % years if weeks: days += weeks * 7 if days: txt += "%sd" % days txt += " " if hours: txt += "%sh" % hours if minutes: txt += "%sm" % minutes if sec and not hours: txt += "%ss" % sec if txt: return txt.strip() else: return "0s"
[docs]def str_day(seconds): txt = "" nsec = int(float(seconds)) year = 365*24*60*60 week = 7*24*60*60 day = 24*60*60 hour = 60*60 minute = 60 #nsec -= nsec * leapfactor years = int(nsec/year) nsec -= years*year weeks = int(nsec/week) nsec -= weeks*week days = int(nsec/day) nsec -= days*day hours = int(nsec/hour) nsec -= hours*hour minutes = int(nsec/minute) sec = nsec - minutes*minute if years: txt = "%sy" % years if weeks: txt += "%sw" % weeks ; return txt if days: txt = "%sd" % days ; return txt if hours: txt = "%sh" % hours ; return txt if minutes: txt = "%sm" % minutes ; return txt if sec: txt = "%ss" % int(sec) if txt: return txt else: return "0s" ## strtotime function
[docs]def get_day(daystr): """ convert string to time. """ try: dmyre = re.search('(\d+)-(\d+)-(\d+)', daystr) (day, month, year) = dmyre.groups() day = int(day) month = int(month) year = int(year) if day <= calendar.monthrange(year, month)[1]: date = "%s %s %s" % (day, bdmonths[month], year) return time.mktime(time.strptime(date, "%d %b %Y")) except AttributeError: return 0 except ValueError: return 0
[docs]def get_hour(daystr): try: hmsre = re.search('(\d+):(\d+):(\d+)', daystr) hours = 60 * 60 * (int(hmsre.group(1))) hoursmin = hours + int(hmsre.group(2)) * 60 hms = hoursmin + int(hmsre.group(3)) except AttributeError: pass except ValueError: pass try: hmre = re.search('(\d+):(\d+)', daystr) hours = 60 * 60 * (int(hmre.group(1))) hms = hours + int(hmre.group(2)) * 60 except AttributeError: return 0 except ValueError: return 0 return hms ## today function
[docs]def today(): """ return time of 0:00 today. """ today = day() ttime = time.strptime(today, "%Y-%m-%d") result = time.mktime(ttime) return result