Python datetime.today() Examples

The following are code examples for showing how to use datetime.today(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    MIT License 6 votes vote down vote up
def test_date_range_normalize(self):
        snap = datetime.today()
        n = 50

        rng = date_range(snap, periods=n, normalize=False, freq='2D')

        offset = timedelta(2)
        values = np.array([snap + i * offset for i in range(n)],
                          dtype='M8[ns]')

        self.assert_(np.array_equal(rng, values))

        rng = date_range(
            '1/1/2000 08:15', periods=n, normalize=False, freq='B')
        the_time = time(8, 15)
        for val in rng:
            self.assert_(val.time() == the_time) 
Example 2
Project: yudi   Author: teambotmax   File: yudi.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIdsx()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"⏩Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩Group : "+str(len(gid))+"\n⏩Teman : "+str(len(teman))+"\n⏩Expired : In "+hari+"\n⏩Version : ARIFISTIFIK\n⏩Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 3
Project: yudi   Author: teambotmax   File: SOLO2.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n◐ Group : "+str(len(gid))+"\n◐ Teman : "+str(len(teman))+"\n◐ Expired : In "+hari+"\n◐ Version : MAX v10\n◐ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n◐ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 4
Project: yudi   Author: teambotmax   File: yudi2.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIdsx()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"⏩Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩Group : "+str(len(gid))+"\n⏩Teman : "+str(len(teman))+"\n⏩Expired : In "+hari+"\n⏩Version : ARIFISTIFIK\n⏩Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 5
Project: os-vm-expire   Author: genouest   File: utils.py    Apache License 2.0 6 votes vote down vote up
def create_timestamp_w_tz_and_offset(timezone=None, days=0, hours=0, minutes=0,
                                     seconds=0):
    """Creates a timestamp with a timezone and offset in days

    :param timezone: Timezone used in creation of timestamp
    :param days: The offset in days
    :param hours: The offset in hours
    :param minutes: The offset in minutes
    :return: a timestamp
    """
    if timezone is None:
        timezone = time.strftime("%z")

    timestamp = '{time}{timezone}'.format(
        time=(datetime.datetime.today() + datetime.timedelta(days=days,
                                                             hours=hours,
                                                             minutes=minutes,
                                                             seconds=seconds)),
        timezone=timezone)

    return timestamp 
Example 6
Project: time_extract   Author: blackbirdco   File: date_render.py    MIT License 6 votes vote down vote up
def nth_day_of_week(self, subtree):
        if subtree.label().startswith('first'):
            n = 0
        if subtree.label().startswith('second'):
            n = 1
        if subtree.label().startswith('third'):
            n = 2
        if subtree.label().startswith('fourth'):
            n = 3
        if subtree.label().startswith('fifth'):
            n = 4
        if subtree.label().startswith('sixth'):
            n = 5
        if subtree.label().startswith('seventh'):
            n = 6

        d = dt.today()
        self.dictionary['timestamp'] = self.next_weekday(d, n) 
Example 7
Project: luci-py   Author: luci   File: testing.py    Apache License 2.0 6 votes vote down vote up
def mock_timezone(tzname):
  """Mocks tzlocal.get_localzone method to always return a given timezone.

  This should be used in combination with mock_datetime_utc in order to achieve
  consistent test results accross timezones if datetime.now, datetime.today or
  date.today functions are used.
  
  Args:
    tzname: Name of the timezone to be used (as passed to pytz.timezone).
  """
  # TODO(sergiyb): Also mock other common libraries, e.g. time, pytz.reference.
  def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
      with mock.patch('tzlocal.get_localzone', lambda: pytz.timezone(tzname)):
        return func(*args, **kwargs)
    return wrapper
  return decorator 
Example 8
Project: luci-py   Author: luci   File: testing.py    Apache License 2.0 6 votes vote down vote up
def mock_timezone(tzname):
  """Mocks tzlocal.get_localzone method to always return a given timezone.

  This should be used in combination with mock_datetime_utc in order to achieve
  consistent test results accross timezones if datetime.now, datetime.today or
  date.today functions are used.
  
  Args:
    tzname: Name of the timezone to be used (as passed to pytz.timezone).
  """
  # TODO(sergiyb): Also mock other common libraries, e.g. time, pytz.reference.
  def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
      with mock.patch('tzlocal.get_localzone', lambda: pytz.timezone(tzname)):
        return func(*args, **kwargs)
    return wrapper
  return decorator 
Example 9
Project: Line-Bot-Protect-And-Selfbot   Author: AbiPutrallg   File: rey.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩ Group : "+str(len(gid))+"\n⏩ Teman : "+str(len(teman))+"\n⏩ Expired : In "+hari+"\n⏩ Version : ANTIJS2\n⏩ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 10
Project: sgx-kms   Author: cloud-security-research   File: utils.py    Apache License 2.0 6 votes vote down vote up
def create_timestamp_w_tz_and_offset(timezone=None, days=0, hours=0, minutes=0,
                                     seconds=0):
    """Creates a timestamp with a timezone and offset in days

    :param timezone: Timezone used in creation of timestamp
    :param days: The offset in days
    :param hours: The offset in hours
    :param minutes: The offset in minutes

    :return a timestamp
    """
    if timezone is None:
        timezone = time.strftime("%z")

    timestamp = '{time}{timezone}'.format(
        time=(datetime.datetime.today() + datetime.timedelta(days=days,
                                                             hours=hours,
                                                             minutes=minutes,
                                                             seconds=seconds)),
        timezone=timezone)

    return timestamp 
Example 11
Project: AntiJS-12-Bot-Python3   Author: AbiPutrallg   File: AntiJS.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,10,7)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = boy.getAllContactIds()
        gid = boy.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"❂͜͡☬➣ ♩ค๓ : "+datetime.strftime(timeNow,'%H:%M:%S')+" ฬīв\n❂͜͡☬➣ งг๏มр : "+str(len(gid))+"\n❂͜͡☬➣ ҭє๓คก : "+str(len(teman))+"\n❂͜͡☬➣ єхрīгє๔ : In "+hari+"\n❂͜͡☬➣ ⅴєгรī๏ก : рұҭђ๏ก3\n❂͜͡☬➣ ҭค๓งงคใ : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n❂͜͡☬➣ гมกҭī๓є : \n • "+bot
        boy.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        boy.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 12
Project: SOLO   Author: stya535   File: SOLO.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n◐ Group : "+str(len(gid))+"\n◐ Teman : "+str(len(teman))+"\n◐ Expired : In "+hari+"\n◐ Version : MAX v10\n◐ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n◐ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 13
Project: KIA   Author: botakboot   File: botak5.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩ Group : "+str(len(gid))+"\n⏩ Teman : "+str(len(teman))+"\n⏩ Expired : In "+hari+"\n⏩ Version : ANTIJS2\n⏩ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 14
Project: reymia   Author: reysebastian   File: rey.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩ Group : "+str(len(gid))+"\n⏩ Teman : "+str(len(teman))+"\n⏩ Expired : In "+hari+"\n⏩ Version : ANTIJS2\n⏩ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 15
Project: cnidaria   Author: sauloal   File: test_timeseries.py    MIT License 6 votes vote down vote up
def test_class_ops_pytz(self):
        tm._skip_if_no_pytz()
        from pytz import timezone

        def compare(x, y):
            self.assertEqual(int(Timestamp(x).value / 1e9), int(Timestamp(y).value / 1e9))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example 16
Project: cnidaria   Author: sauloal   File: test_timeseries.py    MIT License 6 votes vote down vote up
def test_class_ops_dateutil(self):
        tm._skip_if_no_dateutil()
        from dateutil.tz import tzutc

        def compare(x,y):
            self.assertEqual(int(np.round(Timestamp(x).value/1e9)), int(np.round(Timestamp(y).value/1e9)))

        compare(Timestamp.now(),datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(tzutc()))
        compare(Timestamp.utcnow(),datetime.utcnow())
        compare(Timestamp.today(),datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())
        compare(Timestamp.utcfromtimestamp(current_time),
                datetime.utcfromtimestamp(current_time))
        compare(Timestamp.fromtimestamp(current_time),
                datetime.fromtimestamp(current_time))

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(Timestamp.combine(date_component, time_component),
                datetime.combine(date_component, time_component)) 
Example 17
Project: cnidaria   Author: sauloal   File: test_timeseries.py    MIT License 6 votes vote down vote up
def test_date_range_normalize(self):
        snap = datetime.today()
        n = 50

        rng = date_range(snap, periods=n, normalize=False, freq='2D')

        offset = timedelta(2)
        values = np.array([snap + i * offset for i in range(n)],
                          dtype='M8[ns]')

        self.assert_numpy_array_equal(rng, values)

        rng = date_range(
            '1/1/2000 08:15', periods=n, normalize=False, freq='B')
        the_time = time(8, 15)
        for val in rng:
            self.assertEqual(val.time(), the_time) 
Example 18
Project: quantz   Author: zhangyuz   File: miscutils.py    Apache License 2.0 5 votes vote down vote up
def today_yyyymmdd_str():
    """
    获取今天YYYYMMDD格式的日期。
    :return:
    """
    return date_2_str(datetime.today()) 
Example 19
Project: quantz   Author: zhangyuz   File: miscutils.py    Apache License 2.0 5 votes vote down vote up
def today_datetime():
    return datetime.today() 
Example 20
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    MIT License 5 votes vote down vote up
def test_index_to_datetime(self):
        idx = Index(['1/1/2000', '1/2/2000', '1/3/2000'])

        result = idx.to_datetime()
        expected = DatetimeIndex(datetools.to_datetime(idx.values))
        self.assert_(result.equals(expected))

        today = datetime.today()
        idx = Index([today], dtype=object)
        result = idx.to_datetime()
        expected = DatetimeIndex([today])
        self.assert_(result.equals(expected)) 
Example 21
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    MIT License 5 votes vote down vote up
def test_class_ops(self):
        _skip_if_no_pytz()
        import pytz

        def compare(x,y):
            self.assertEqual(int(Timestamp(x).value/1e9), int(Timestamp(y).value/1e9))

        compare(Timestamp.now(),datetime.now())
        compare(Timestamp.now('UTC'),datetime.now(pytz.timezone('UTC')))
        compare(Timestamp.utcnow(),datetime.utcnow())
        compare(Timestamp.today(),datetime.today()) 
Example 22
Project: EvapoTranspiration   Author: linuxha   File: weatherCustom.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def XmmFromLogs(t):
    ydate = (datetime.today() - datetime.utcfromtimestamp(0)).days - 1
    filenames = next(os.walk(logsPath))[2]
    for x in filenames:
        ldate = x
        if ldate == str(ydate):
            fpath = x
        #
    #
    yET = json.load(open(ETPath + '/' + fpath))
    tET = [0] * len(yET)
    logs = json.load(open(logsPath + '/' + fpath))
    if debug != 0: print >>sys.stderr, "E: json load %s/%s (%s)" % (logsPath, fpath, logs)
    l = len(t['mmTime'])
    ydur = [-1] * l
    ymm = [-1] * l
    for x in logs:
        if int(x[0]) == pid:
            ydur[safe_int(x[1])] += safe_int(x[2])
        #
    #
    for x in range(l):
        if t['mmTime'][x]:
            ymm[x] = round(safe_float(yET[safe_int(t['crop'][x])]) - ydur[x] / safe_float(t['mmTime'][x]), 4) * -1
            tET[int(t['crop'][x])] = ymm[x]
        else:
            ymm[x] = 0
        #
    #
    return (ymm, tET)
#

# 
Example 23
Project: heimdalerp   Author: heimdalerp   File: validators.py    ISC License 5 votes vote down vote up
def date_is_future(value):
    if isinstance(value, datetime.date):
        if value <= datetime.date.today():
            raise ValidationError(
                _("The date entered must be greater than today.")
            )
    elif isinstance(value, datetime.datetime):
        if value.date() <= datetime.today():
            raise ValidationError(
                _("The date entered must be greater than today.")
            )
    else:
        raise ValidationError(
            _("The value entered isn't a valid type of date or datetime.")
        ) 
Example 24
Project: heimdalerp   Author: heimdalerp   File: validators.py    ISC License 5 votes vote down vote up
def date_is_present_or_future(value):
    if isinstance(value, datetime.date):
        if value < datetime.date.today():
            raise ValidationError(
                _("The date entered must be today or lesser.")
            )
    elif isinstance(value, datetime.datetime):
        if value.date() < datetime.datetime.today():
            raise ValidationError(
                _("The date entered must be today or greater.")
            )
    else:
        raise ValidationError(
            _("The value entered isn't a valid type of date or datetime.")
        ) 
Example 25
Project: heimdalerp   Author: heimdalerp   File: validators.py    ISC License 5 votes vote down vote up
def date_is_past(value):
    if isinstance(value, datetime.date):
        if value >= datetime.date.today():
            raise ValidationError(
                _("The date entered must be today or lesser.")
            )
    elif isinstance(value, datetime.datetime):
        if value.date() >= datetime.datetime.today():
            raise ValidationError(
                _("The date entered must be lesser than today.")
            )
    else:
        raise ValidationError(
            _("The value entered isn't a valid type of date or datetime.")
        ) 
Example 26
Project: heimdalerp   Author: heimdalerp   File: validators.py    ISC License 5 votes vote down vote up
def date_is_present_or_past(value):
    if isinstance(value, datetime.date):
        if value > datetime.date.today():
            raise ValidationError(
                _("The date entered must be today or lesser.")
            )
    elif isinstance(value, datetime.datetime):
        if value.date() > datetime.datetime.today():
            raise ValidationError(
                _("The date entered must be today or lesser.")
            )
    else:
        raise ValidationError(
            _("The value entered isn't a valid type of date or datetime.")
        ) 
Example 27
Project: invader   Author: entynetproject   File: helpers.py    MIT License 5 votes vote down vote up
def generate_random_script_var_name(origvariname,globDebug=False):
    if globDebug:
	    return origvariname
    else:
	    hash_object=hashlib.sha1(str(origvariname)+str(globentropy)).hexdigest()
    return hash_object[:-datetime.today().day] 
Example 28
Project: laurence-bot   Author: c4software   File: models.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, username, text):
        if not username or not text:
            raise Exception("All field are required")

        self.username = username
        self.text = text
        self.datetime = datetime.datetime.today() 
Example 29
Project: laurence-bot   Author: c4software   File: models.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, username, planned_time, commande):
        if not username or not planned_time or not commande:
            raise Exception("All fields are required")

        self.username = username
        self.planned_time = planned_time
        self.commande = commande
        self.last_execution = datetime.today() 
Example 30
Project: os-vm-expire   Author: genouest   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_tomorrow_timestamp():
    tomorrow = (datetime.today() + datetime.timedelta(days=1))
    return tomorrow.isoformat() 
Example 31
Project: time_extract   Author: blackbirdco   File: date_render.py    MIT License 5 votes vote down vote up
def today(self, subtree):
        currentTime = dt.today()
        currentTimestamp = mktime(currentTime.timetuple())
        self.dictionary['timestamp'] = currentTimestamp 
Example 32
Project: time_extract   Author: blackbirdco   File: date_render.py    MIT License 5 votes vote down vote up
def tommorow(self, subtree):
        dayAfterTime = dt.today() + timedelta(days=1)
        dayAfterTimestamp = mktime(dayAfterTime.timetuple())
        self.dictionary['timestamp'] = dayAfterTimestamp 
Example 33
Project: time_extract   Author: blackbirdco   File: date_render.py    MIT License 5 votes vote down vote up
def yesterday(self, subtree):
        day_before_time = dt.today() + timedelta(days=-1)
        day_before_timestamp = mktime(day_before_time.timetuple())
        self.dictionary['timestamp'] = day_before_timestamp 
Example 34
Project: time_extract   Author: blackbirdco   File: date_render.py    MIT License 5 votes vote down vote up
def noon(self, subtree):
        if('timestamp' not in self.dictionary):
            self.dictionary['timestamp'] = mktime(dt.today().timetuple())
        self.dictionary['timestamp'] += 12 * 3600
        self.dictionary['hours'] = '12' 
Example 35
Project: alfredToday   Author: jeeftor   File: quickstart.py    MIT License 5 votes vote down vote up
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
    	'calendar-alfred-today.json')


    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials 
Example 36
Project: sgx-kms   Author: cloud-security-research   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_tomorrow_timestamp():
    tomorrow = (datetime.today() + datetime.timedelta(days=1))
    return tomorrow.isoformat() 
Example 37
Project: time-travel   Author: snudler6   File: datetime_patcher.py    MIT License 5 votes vote down vote up
def today(cls):
        """Return today's date."""
        result = cls._now()
        return date_to_fakedate(result) 
Example 38
Project: time-travel   Author: snudler6   File: datetime_patcher.py    MIT License 5 votes vote down vote up
def today(cls):
        """Return a datetime object representing current time."""
        return cls.now(tz=None) 
Example 39
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_datetime_patch_set_time():
    with TimeTravel(modules_to_patch=[__name__]) as t:

        assert datetime_cls.today() == datetime_cls.fromtimestamp(_t(0))
        t.clock.time = _t(1000)
        assert datetime_cls.today() == datetime_cls.fromtimestamp(_t(1000)) 
Example 40
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_patch_stop_afer_scope_end():
    with TimeTravel(modules_to_patch=__name__) as t:

        assert datetime_cls.now() == datetime_cls.fromtimestamp(_t(0))
        t.clock.time = _t(1000)
        assert datetime_cls.today() == datetime_cls.fromtimestamp(_t(1000))

    assert time.time() != _t(1000)
    assert datetime_cls.today() != datetime_cls.fromtimestamp(_t(1000)) 
Example 41
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_inner_importing_of_datetime():
    with TimeTravel(modules_to_patch=__name__):
        import datetime
        assert datetime.date.today() == datetime.date.fromtimestamp(_t(0)) 
Example 42
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_sleep_changing_datetime_now():
    with TimeTravel(modules_to_patch=__name__):
        assert datetime_cls.today() == datetime_cls.fromtimestamp(_t(0))
        time.sleep(150)
        assert datetime_cls.now() == datetime_cls.fromtimestamp(_t(150)) 
Example 43
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_select_no_timeout():
    with TimeTravel(modules_to_patch=__name__) as t:
        sock = socket.socket()

        t.add_future_event(2, sock, t.event_types.select.WRITE)

        now = t.clock.time
        assert select.select([], [sock], []) == ([], [sock], [])
        assert time.time() == now + 2
        assert datetime_cls.today() == datetime_cls.fromtimestamp(now + 2) 
Example 44
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_select_with_timeout():
    with TimeTravel(modules_to_patch=__name__) as t:
        sock = socket.socket()

        t.add_future_event(2, sock, t.event_types.select.EXCEPTIONAL)

        now = t.clock.time
        assert select.select([], [], [sock], 6) == ([], [], [sock])
        assert time.time() == now + 2
        assert datetime_cls.today() == datetime_cls.fromtimestamp(now + 2) 
Example 45
Project: time-travel   Author: snudler6   File: test_time_travel.py    MIT License 5 votes vote down vote up
def test_select_timeout_occurring():
    with TimeTravel(modules_to_patch=__name__) as t:
        sock = socket.socket()

        t.add_future_event(10, sock, t.event_types.select.READ)

        now = t.clock.time
        assert select.select([sock], [], [], 6) == ([], [], [])
        assert time.time() == now + 6
        assert datetime_cls.today() == datetime_cls.fromtimestamp(now + 6) 
Example 46
Project: cnidaria   Author: sauloal   File: test_timeseries.py    MIT License 5 votes vote down vote up
def test_index_to_datetime(self):
        idx = Index(['1/1/2000', '1/2/2000', '1/3/2000'])

        result = idx.to_datetime()
        expected = DatetimeIndex(datetools.to_datetime(idx.values))
        self.assertTrue(result.equals(expected))

        today = datetime.today()
        idx = Index([today], dtype=object)
        result = idx.to_datetime()
        expected = DatetimeIndex([today])
        self.assertTrue(result.equals(expected)) 
Example 47
Project: fract   Author: ktmrmshk   File: cmdline_test.py    Apache License 2.0 5 votes vote down vote up
def test_RunTestcases(self):
        '''
        Scenario
        1. run commmand the same as $ fract -v run -i testcase.json
        2. check if frdiff*.yaml fret*.json frsummary*.txt three files exist.
        '''
        logging.info('Testing: Run testcases')
        self.COMMAND = 'python3 {} -v run -i {}'.format(fraui_path, self.TESTCASE)
        now = datetime.today()
        midstart = int(now.strftime('%Y%m%d%H%M%S%f'))
        self.do_cmd(self.COMMAND)
        now = datetime.today()
        midafter = int(now.strftime('%Y%m%d%H%M%S%f'))
        listResult = self.getTestResultsFiles(basePath)
        filecount = 0
        for i in listResult:
            tmpFilename = os.path.basename(i).split('.')[0]
            logging.debug('Filename except extension: ' + tmpFilename)
            if 'frdiff' in tmpFilename:
                tmpID = int(tmpFilename[6:])
                if tmpID < midafter and tmpID > midstart:
                    filecount += 1
                    with open(i, mode='r') as rf:
                        contents = rf.read()
                        self.assertTrue(contents.index('Ghost: fract.akamaized-staging.net') > 0)
            if 'fret' in tmpFilename:
                tmpID = int(tmpFilename[4:])
                if tmpID < midafter and tmpID > midstart:
                    filecount += 1
                    with open(i, mode='r') as rf:
                        contents = rf.read()
                        self.assertTrue(contents.index('X-Akamai-Session-Info') > 0)
            if 'frsummary' in tmpFilename:
                tmpID = int(tmpFilename[9:])
                if tmpID < midafter and tmpID > midstart:
                    filecount += 1
                    with open(i, mode='r') as rf:
                        contents = rf.read()
                        self.assertTrue(contents.index('Summary') > 0)
        self.assertTrue(filecount == 3) 
Example 48
Project: german-weather-warnings   Author: sirko85   File: weather.py    Apache License 2.0 4 votes vote down vote up
def __downloadWeatherWarnings(self):
		"""
			load all weatherwarnings from today
			TODO load all weatherwarnings since last download
		"""
		directory = '/gds/gds/specials/alerts/cap/GER/status/'
		self.__dwd_ftp.cwd(directory)

		cursor = self.__db.cursor()
		sql_command = """SELECT created_at FROM checks ORDER BY created_at DESC LIMIT 1"""
		cursor.execute(sql_command)
		res = cursor.fetchone()
		if(res is None):
			print('No date found... starting download from today 00 o\'Clock.')
			sql_command = """INSERT INTO checks(created_at) VALUES ({created_at})"""
			sql_command = sql_command.format(created_at="(datetime('now','localtime'))")
			cursor.execute(sql_command)
			self.__db.commit()
			current_time = datetime.today()
			current_time = current_time.replace(hour=0, minute=0, second=0, microsecond=0)
		else:
			current_time = datetime.strptime(res[0],'%Y-%m-%d %H:%M:%S')

		tag = current_time.day
		if(tag < 10):
			tag = '0' + str(tag)

		stunde = current_time.hour
		if(stunde < 10):
			stunde = '0' + str(stunde)

		minute = current_time.minute
		if(minute < 10):
			minute = '0' + str(minute)

		current_day = str(current_time.year) + str(current_time.month) + str(tag) + str(stunde) + str(minute)
		filenames = self.__dwd_ftp.nlst()
		filenames.sort(reverse=True)
		for filename in filenames:
			current_file_time = datetime.strptime(filename[13:25],'%Y%m%d%H%M%S')
			if(current_file_time <= current_time):
				continue

			print('"'+filename+ '" downloaded.')
			file = open(self.__download_dir + filename, 'wb')
			self.__dwd_ftp.retrbinary('RETR ' + filename, file.write)
			file.close()
			with zipfile.ZipFile(self.__download_dir + filename) as zf:
				zf.extractall(self.__download_dir)

			os.remove(self.__download_dir + filename)

		self.__dwd_ftp.close()
		return True 
Example 49
Project: time_extract   Author: blackbirdco   File: date_render.py    MIT License 4 votes vote down vote up
def to_i(self, arg):
        for subtree in self.tree.subtrees():
            if subtree.label() == 'metadata':
                self.metadata_text(subtree)

            if subtree.label()[:-4] == self.metadata_name:
                self.dictionary['metadata'] = self.metadata_name

            if subtree.label() == 'todayItem':
                self.today(subtree)

            if subtree.label() == 'tomorrowItem':
                self.tommorow(subtree)

            if subtree.label() == 'yesterdayItem':
                self.yesterday(subtree)

            if subtree.label() == 'middayItem':
                self.noon(subtree)

            if subtree.label() == 'midnightItem':
                self.midnight(subtree)

            if 'DayOfWeekItem' in subtree.label():
                self.nth_day_of_week(subtree)

            if subtree.label() == 'dayValueItem':
                self.dictionary['day'] = ' '.join(subtree.leaves())

            if subtree.label() == 'monthValueItem':
                self.dictionary['month'] = ' '.join(subtree.leaves())
        
        if (('day' in self.dictionary) or ('month' in self.dictionary)):
            dateStr = ''
            if ('day' in self.dictionary):
                dateStr += self.dictionary['day'] + ' ' 
            if ('month' in self.dictionary):
                dateStr += self.dictionary['month'] + ' '
            dateParser = dateparser.parse(dateStr)
            dateTimestamp =  mktime(dateParser.timetuple())
            self.dictionary['timestamp'] = dateTimestamp
            if ('hours' in self.dictionary):
                self.dictionary['timestamp'] += int(self.dictionary['hours']) * 3600
        return self.dictionary 
Example 50
Project: WebCredibility   Author: DeFacto   File: scrap.py    Apache License 2.0 4 votes vote down vote up
def get_wayback_tot_via_memento(self, w, urlalt=None):
        '''
        returns archive information for the URL (via memento protocol)
        :param w: the penalization value for domain search
        :param urlalt: an alternative URL (e.g., the URL domain)
        :return: number of years the URL was cached, since the caching started.
        '''
        k = 0
        y = 0
        try:
            if urlalt is None:
                urlalt = self.url
                w = 1.0
            out = self.__query_memento(urlalt)
            if out['mementos']:
                t1 = Timestamp(out['mementos']['first']['datetime'], tz=None)
                try:
                    t2 = Timestamp(out['mementos']['prev']['datetime'], tz=None)
                except:
                    t2 = t1
                t3 = Timestamp(out['mementos']['closest']['datetime'], tz=None)
                try:
                    t4 = Timestamp(out['mementos']['next']['datetime'], tz=None)
                except:
                    t4 = t3
                t5 = Timestamp(out['mementos']['last']['datetime'], tz=None)


                d1 = abs(t2 - t1) + dt2.timedelta(days=1)
                d2 = abs(t4 - t3) + dt2.timedelta(days=1)

                l = 1 / (np.log(d1.days * d2.days) + 1)

                age_years = abs(t5.year - t1.year) + 1
                today = datetime.today()
                most_recent_update = diff_month(today, t5) + 1

                k = (l + np.log(age_years) + (1 / most_recent_update)) * w

                #print(t1, t2, t3, t4, t5)

                #k = (t1.year - t2.year)
                #k = k * w
                y = t5.year

            #print(k)
            return k, y
        except Exception as e:
            config.logger.error(repr(e))
            raise 
Example 51
Project: RFHO   Author: lucfra   File: save_and_load.py    MIT License 4 votes vote down vote up
def __init__(self, experiment_names, *items, append_date_to_name=True,
                 root_directory=FOLDER_NAMINGS['EXP_ROOT'],
                 timer=None, do_print=True, collect_data=True, default_overwrite=False):
        """
        Initialize a saver to collect data. (Intended to be used together with OnlinePlotStream.)

        :param experiment_names: string or list of strings which represent the name of the folder (and sub-folders)
                                    experiment oand
        :param items: a list of (from pairs to at most) 5-tuples that represent the things you want to save.
                      The first arg of each tuple should be a string that will be the key of the save_dict.
                      Then there can be either a callable with signature (step) -> None
                      Should pass the various args in ths order:
                          fetches: tensor or list of tensors to compute;
                          feeds (optional): to be passed to tf.Session.run. Can be a
                          callable with signature (step) -> feed_dict
                          options (optional): to be passed to tf.Session.run
                          run_metadata (optional): to be passed to tf.Session.run
        :param timer: optional timer object. If None creates a new one. If false does not register time.
                        If None or Timer it adds to the save_dict an entry time that record elapsed_time.
                        The time required to perform data collection and saving are not counted, since typically
                        the aim is to record the true algorithm execution time!
        :param root_directory: string, name of root directory (default ~HOME/Experiments)
        :param do_print: (optional, default True) will print by default `save_dict` each time method `save` is executed
        :param collect_data: (optional, default True) will save by default `save_dict` each time
                            method `save` is executed
        """
        experiment_names = as_list(experiment_names)
        if append_date_to_name:
            from datetime import datetime
            experiment_names += [datetime.today().strftime('%d-%m-%y__%Hh%Mm')]
        self.experiment_names = list(experiment_names)

        if not os.path.isabs(experiment_names[0]):
            self.directory = join_paths(root_directory)  # otherwise assume no use of root_directory
            if collect_data:
                check_or_create_dir(root_directory, notebook_mode=False)
        else: self.directory = ''
        for name in self.experiment_names:
            self.directory = join_paths(self.directory, name)
            check_or_create_dir(self.directory, notebook_mode=False, create=collect_data)

        self.do_print = do_print
        self.collect_data = collect_data
        self.default_overwrite = default_overwrite

        assert isinstance(timer, Timer) or timer is None or timer is False, 'timer param not good...'

        if timer is None:
            timer = Timer()

        self.timer = timer

        self.clear_items()

        self.add_items(*items)

    # noinspection PyAttributeOutsideInit 
Example 52
Project: fract   Author: ktmrmshk   File: cmdline_test.py    Apache License 2.0 4 votes vote down vote up
def test_RedirectLoop(self):
        '''
        Scenario
        1. run command the same as $ fract testredirectloop -i looplist.txt -o loopsummary.txt -r loopresult.json -s fract.akamaized.net -m 3
        '''
        logging.info('Testing: Export Redirect Summary')
        self.COMMAND = 'python3 {} -v testredirectloop -i {} -s {} -o {} -d {} -m {}'.format(fraui_path, self.REDIRECTLOOP_INPUT, self.REDIRECTLOOP_SUMMARY, self.REDIRECTLOOP_RESULT, "fract.akamaized.net", 3)
        self.do_cmd(self.COMMAND)
        self.assertTrue(os.path.isfile(self.REDIRECTLOOP_RESULT.strip('"')))
        self.assertTrue(os.path.isfile(self.REDIRECTLOOP_SUMMARY.strip('"')))
        if os.path.isfile(self.REDIRECTLOOP_SUMMARY):
            with open(self.REDIRECTLOOP_SUMMARY, mode='r') as rf:
                contents = rf.read()
                self.assertTrue(contents.index('Maximum Value 3') > 0)
        if os.path.isfile(self.REDIRECTION_RESULT):
            with open(self.REDIRECTION_RESULT, mode='r') as rf:
                contents = rf.read()
                self.assertTrue(contents.index('Threshold') > 0)
                self.assertTrue(contents.index('Depth') > 0)
                self.assertTrue(contents.index('301') > 0)
                self.assertTrue(contents.index('302') > 0)
                self.assertTrue(contents.index('303') > 0)
                self.assertTrue(contents.index('307') > 0)
        now = datetime.today()
        midstart = int(now.strftime('%Y%m%d%H%M%S%f'))
        self.COMMAND = 'python3 {} -v testredirectloop -i {}'.format(fraui_path, self.REDIRECTLOOP_INPUT)
        self.do_cmd(self.COMMAND)
        now = datetime.today()
        midafter = int(now.strftime('%Y%m%d%H%M%S%f'))
        listResult = self.getTestResultsFiles(basePath)
        filecount = 0
        for i in listResult:
            tmpFilename = os.path.basename(i).split('.')[0]
            logging.debug('Filename except extension: ' + tmpFilename)
            if 'loopret' in tmpFilename:
                tmpID = int(tmpFilename[7:])
                if tmpID < midafter and tmpID > midstart:
                    filecount += 1
                    with open(i, mode='r') as rf:
                        contents = rf.read()
                        self.assertTrue(contents.index('Depth') > 0)
            if 'loopsummary' in tmpFilename:
                tmpID = int(tmpFilename[11:])
                if tmpID < midafter and tmpID > midstart:
                    filecount += 1
                    with open(i, mode='r') as rf:
                        contents = rf.read()
                        self.assertTrue(contents.index('Summary') > 0)
        self.assertTrue(filecount == 2)
    ### 2019/04/08 testredirectloop end


# edge redirector cost check support