Python datetime.today() Examples

The following are 13 code examples for showing how to use datetime.today(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    License: 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: ajs2   Author: arifistifik   File: ajs.py    License: 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 3
Project: sgx-kms   Author: cloud-security-research   File: utils.py    License: 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 4
Project: python-barbicanclient   Author: openstack   File: utils.py    License: 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 5
Project: barbican   Author: openstack   File: utils.py    License: 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: dipper   Author: monarch-initiative   File: test_dataset.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_version_level_created(self):
        triples = list(self.dataset.graph.triples(
            (self.version_level_IRI, self.iri_created, None)))
        self.assertTrue(len(triples) == 1,
                        "didn't get exactly 1 version level created triple")
        self.assertEqual(triples[0][2],
                         Literal(datetime.today().strftime("%Y%m%d"),
                                 datatype=XSD.date),
                         "version level created triple has the wrong timestamp") 
Example 7
Project: dipper   Author: monarch-initiative   File: test_dataset.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_distribution_level_created(self):
        triples = list(self.dataset.graph.triples(
            (self.distribution_level_IRI_ttl, self.iri_created, None)))
        self.assertTrue(len(triples) == 1,
                        "didn't get exactly 1 version level type created triple")
        self.assertEqual(triples[0][2], Literal(datetime.today().strftime("%Y%m%d"),
                                                datatype=XSD.date)) 
Example 8
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    License: 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 9
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    License: 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 10
Project: sgx-kms   Author: cloud-security-research   File: utils.py    License: 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 11
Project: python-barbicanclient   Author: openstack   File: utils.py    License: 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 12
Project: barbican   Author: openstack   File: utils.py    License: 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 13
Project: RFHO   Author: lucfra   File: save_and_load.py    License: 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