Python datetime.datetime.today() Examples

The following are 30 code examples for showing how to use datetime.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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: ffplayout-engine   Author: ffplayout   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_time(time_format):
    """
    get different time formats:
        - full_sec > current time in seconds
        - stamp > current date time in seconds
        - else > current time in HH:MM:SS
    """
    t = datetime.today()

    if time_format == 'full_sec':
        return t.hour * 3600 + t.minute * 60 + t.second \
             + t.microsecond / 1000000
    elif time_format == 'stamp':
        return float(datetime.now().timestamp())
    else:
        return t.strftime('%H:%M:%S')


# ------------------------------------------------------------------------------
# default variables and values
# ------------------------------------------------------------------------------ 
Example 2
Project: ProxHTTPSProxyMII   Author: wheever   File: ProxyTool.py    License: MIT License 6 votes vote down vote up
def sendout_error(self, url, code, message=None, explain=None):
        "Modified from http.server.send_error() for customized display"
        try:
            shortmsg, longmsg = self.responses[code]
        except KeyError:
            shortmsg, longmsg = '???', '???'
        if message is None:
            message = shortmsg
        if explain is None:
            explain = longmsg
        content = (message_format %
                   {'code': code, 'message': message, 'explain': explain,
                    'url': url, 'now': datetime.today(), 'server': self.server_version})
        body = content.encode('UTF-8', 'replace')
        self.send_response_only(code, message)
        self.send_header("Content-Type", self.error_content_type)
        self.send_header('Content-Length', int(len(body)))
        self.end_headers()
        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
            self.wfile.write(body) 
Example 3
Project: seqr   Author: macarthur-lab   File: external_api_2_3_tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_mme_metrics_proxy(self):
        url = '/api/matchmaker/v1/metrics'

        self._check_mme_authenticated(url)

        response = self._make_mme_request(url, 'get')
        self.assertEqual(response.status_code, 200)
        self.assertDictEqual(response.json(), {
            'metrics': {
                'numberOfCases': 3,
                'numberOfSubmitters': 2,
                'numberOfUniqueGenes': 4,
                'numberOfUniqueFeatures': 4,
                'numberOfRequestsReceived': 3,
                'numberOfPotentialMatchesSent': 1,
                'dateGenerated': datetime.today().strftime('%Y-%m-%d'),
            }
        }) 
Example 4
Project: openSUSE-release-tools   Author: openSUSE   File: abichecker-dbcli.py    License: GNU General Public License v2.0 6 votes vote down vote up
def do_prune(self, subcmd, opts, days):
        """${cmd_name}: prune old records

        ${cmd_usage}
        ${cmd_option_list}
        """

        oldest = datetime.today() - timedelta(days = 365)

        requests = self.session.query(DB.Request).filter(DB.Request.t_updated < oldest)
        for req in requests:
            for a in req.abichecks:
                self.logger.info('prune  %s %s %s', req.id, a.dst_project, a.dst_package)
                for r in a.reports:
                    fn = os.path.join(CACHEDIR, r.htmlreport)
                    if os.path.exists(fn):
                        self.logger.info('removing %s', r.htmlreport)
                        os.unlink(fn)
            self.session.delete(req)
        self.session.commit() 
Example 5
Project: recruit   Author: Frank-qlu   File: test_tools.py    License: Apache License 2.0 6 votes vote down vote up
def test_datetime_bool(self, cache):
        # GH13176
        with pytest.raises(TypeError):
            to_datetime(False)
        assert to_datetime(False, errors="coerce", cache=cache) is NaT
        assert to_datetime(False, errors="ignore", cache=cache) is False
        with pytest.raises(TypeError):
            to_datetime(True)
        assert to_datetime(True, errors="coerce", cache=cache) is NaT
        assert to_datetime(True, errors="ignore", cache=cache) is True
        with pytest.raises(TypeError):
            to_datetime([False, datetime.today()], cache=cache)
        with pytest.raises(TypeError):
            to_datetime(['20130101', True], cache=cache)
        tm.assert_index_equal(to_datetime([0, False, NaT, 0.0],
                                          errors="coerce", cache=cache),
                              DatetimeIndex([to_datetime(0, cache=cache),
                                             NaT,
                                             NaT,
                                             to_datetime(0, cache=cache)])) 
Example 6
Project: recruit   Author: Frank-qlu   File: test_date_range.py    License: Apache License 2.0 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 = DatetimeIndex([snap + i * offset for i in range(n)])

        tm.assert_index_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:
            assert val.time() == the_time 
Example 7
Project: recruit   Author: Frank-qlu   File: test_strings.py    License: Apache License 2.0 6 votes vote down vote up
def test_title(self):
        values = Series(["FOO", "BAR", NA, "Blah", "blurg"])

        result = values.str.title()
        exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"])
        tm.assert_series_equal(result, exp)

        # mixed
        mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None,
                        1, 2.])
        mixed = mixed.str.title()
        exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA])
        tm.assert_almost_equal(mixed, exp)

        # unicode
        values = Series([u("FOO"), NA, u("bar"), u("Blurg")])

        results = values.str.title()
        exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")])

        tm.assert_series_equal(results, exp) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_strings.py    License: Apache License 2.0 6 votes vote down vote up
def test_capitalize(self):
        values = Series(["FOO", "BAR", NA, "Blah", "blurg"])
        result = values.str.capitalize()
        exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"])
        tm.assert_series_equal(result, exp)

        # mixed
        mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None,
                        1, 2.])
        mixed = mixed.str.capitalize()
        exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA])
        tm.assert_almost_equal(mixed, exp)

        # unicode
        values = Series([u("FOO"), NA, u("bar"), u("Blurg")])
        results = values.str.capitalize()
        exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")])
        tm.assert_series_equal(results, exp) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_strings.py    License: Apache License 2.0 6 votes vote down vote up
def test_len(self):
        values = Series(['foo', 'fooo', 'fooooo', np.nan, 'fooooooo'])

        result = values.str.len()
        exp = values.map(lambda x: len(x) if notna(x) else NA)
        tm.assert_series_equal(result, exp)

        # mixed
        mixed = Series(['a_b', NA, 'asdf_cas_asdf', True, datetime.today(),
                        'foo', None, 1, 2.])

        rs = Series(mixed).str.len()
        xp = Series([3, NA, 13, NA, NA, 3, NA, NA, NA])

        assert isinstance(rs, Series)
        tm.assert_almost_equal(rs, xp)

        # unicode
        values = Series([u('foo'), u('fooo'), u('fooooo'), np.nan, u(
            'fooooooo')])

        result = values.str.len()
        exp = values.map(lambda x: len(x) if notna(x) else NA)
        tm.assert_series_equal(result, exp) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_strings.py    License: Apache License 2.0 6 votes vote down vote up
def test_findall(self):
        values = Series(['fooBAD__barBAD', NA, 'foo', 'BAD'])

        result = values.str.findall('BAD[_]*')
        exp = Series([['BAD__', 'BAD'], NA, [], ['BAD']])
        tm.assert_almost_equal(result, exp)

        # mixed
        mixed = Series(['fooBAD__barBAD', NA, 'foo', True, datetime.today(),
                        'BAD', None, 1, 2.])

        rs = Series(mixed).str.findall('BAD[_]*')
        xp = Series([['BAD__', 'BAD'], NA, [], NA, NA, ['BAD'], NA, NA, NA])

        assert isinstance(rs, Series)
        tm.assert_almost_equal(rs, xp)

        # unicode
        values = Series([u('fooBAD__barBAD'), NA, u('foo'), u('BAD')])

        result = values.str.findall('BAD[_]*')
        exp = Series([[u('BAD__'), u('BAD')], NA, [], [u('BAD')]])
        tm.assert_almost_equal(result, exp) 
Example 11
Project: recruit   Author: Frank-qlu   File: test_strings.py    License: Apache License 2.0 6 votes vote down vote up
def test_strip_lstrip_rstrip_mixed(self):
        # mixed
        mixed = Series(['  aa  ', NA, ' bb \t\n', True, datetime.today(), None,
                        1, 2.])

        rs = Series(mixed).str.strip()
        xp = Series(['aa', NA, 'bb', NA, NA, NA, NA, NA])

        assert isinstance(rs, Series)
        tm.assert_almost_equal(rs, xp)

        rs = Series(mixed).str.lstrip()
        xp = Series(['aa  ', NA, 'bb \t\n', NA, NA, NA, NA, NA])

        assert isinstance(rs, Series)
        tm.assert_almost_equal(rs, xp)

        rs = Series(mixed).str.rstrip()
        xp = Series(['  aa', NA, ' bb', NA, NA, NA, NA, NA])

        assert isinstance(rs, Series)
        tm.assert_almost_equal(rs, xp) 
Example 12
Project: recruit   Author: Frank-qlu   File: test_timestamp.py    License: Apache License 2.0 6 votes vote down vote up
def test_today(self):
        ts_from_string = Timestamp('today')
        ts_from_method = Timestamp.today()
        ts_datetime = datetime.today()

        ts_from_string_tz = Timestamp('today', tz='US/Eastern')
        ts_from_method_tz = Timestamp.today(tz='US/Eastern')

        # Check that the delta between the times is less than 1s (arbitrarily
        # small)
        delta = Timedelta(seconds=1)
        assert abs(ts_from_method - ts_from_string) < delta
        assert abs(ts_datetime - ts_from_method) < delta
        assert abs(ts_from_method_tz - ts_from_string_tz) < delta
        assert (abs(ts_from_string_tz.tz_localize(None) -
                    ts_from_method_tz.tz_localize(None)) < delta) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_timestamp.py    License: Apache License 2.0 6 votes vote down vote up
def test_class_ops_dateutil(self):
        def compare(x, y):
            assert (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 14
Project: dipper   Author: monarch-initiative   File: Dataset.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _set_version_level_triples(self):
        self.model.addType(self.version_level_curie, self.globaltt['Dataset'])
        self.graph.addTriple(self.version_level_curie, self.globaltt['title'],
                             self.ingest_title +
                             " Monarch version " +
                             self.data_release_version,
                             True)
        if self.ingest_description is not None:
            self.model.addDescription(self.version_level_curie,
                                      self.ingest_description)
        self.graph.addTriple(self.version_level_curie, self.globaltt['Date Created'],
                             Literal(datetime.today().strftime("%Y%m%d"),
                                     datatype=XSD.date))
        self.graph.addTriple(self.version_level_curie, self.globaltt['version'],
                             Literal(self.data_release_version, datatype=XSD.date))
        self.graph.addTriple(self.version_level_curie, self.globaltt['creator'],
                             self.curie_map.get(""))  # eval's to MI.org
        self.graph.addTriple(self.version_level_curie, self.globaltt['Publisher'],
                             self.curie_map.get(""))  # eval's to MI.org
        self.graph.addTriple(self.version_level_curie, self.globaltt['isVersionOf'],
                             self.summary_level_curie, object_is_literal=False)
        self.graph.addTriple(self.version_level_curie,
                             self.globaltt['distribution'],
                             self.distribution_level_turtle_curie,
                             object_is_literal=False) 
Example 15
Project: iquery   Author: protream   File: trains.py    License: MIT License 6 votes vote down vote up
def _valid_date(self):
        """Check and return a valid query date."""
        date = self._parse_date(self.date)

        if not date:
            exit_after_echo(INVALID_DATE)

        try:
            date = datetime.strptime(date, '%Y%m%d')
        except ValueError:
            exit_after_echo(INVALID_DATE)

        # A valid query date should within 50 days.
        offset = date - datetime.today()
        if offset.days not in range(-1, 50):
            exit_after_echo(INVALID_DATE)

        return datetime.strftime(date, '%Y-%m-%d') 
Example 16
Project: iquery   Author: protream   File: trains.py    License: MIT License 6 votes vote down vote up
def _parse_date(date):
        """Parse from the user input `date`.

        e.g. current year 2016:
           input 6-26, 626, ... return 2016626
           input 2016-6-26, 2016/6/26, ... retrun 2016626

        This fn wouldn't check the date, it only gather the number as a string.
        """
        result = ''.join(re.findall('\d', date))
        l = len(result)

        # User only input month and day, eg 6-1, 6.26, 0626...
        if l in (2, 3, 4):
            year = str(datetime.today().year)
            return year + result

        # User input full format date, eg 201661, 2016-6-26, 20160626...
        if l in (6, 7, 8):
            return result

        return '' 
Example 17
Project: daimaduan.com   Author: DoubleCiti   File: sites.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def index():
    page = get_page()
    pagination = Paste.objects(is_private=False).order_by('-updated_at').paginate(page=page, per_page=20)

    print datetime.today()

    return render_template('index.html',
                           pagination=pagination,
                           hot_pastes=Paste.objects(is_private=False).order_by('-views')[:10],
                           pastes_count=Paste.objects().count(),
                           comments_count=Comment.objects().count(),
                           users_count=User.objects().count(),
                           syntax_count=Syntax.objects().count(),
                           bookmarks_count=Bookmark.objects().count(),
                           users_increased=User.objects(created_at__gt=date.today()).count(),
                           pastes_increased=Paste.objects(created_at__gt=date.today()).count(),
                           comments_increased=Comment.objects(created_at__gt=date.today()).count(),
                           bookmarks_increased=Bookmark.objects(created_at__gt=date.today()).count(),
                           tags=Tag.objects().order_by('-popularity')[:10]) 
Example 18
Project: myhdl   Author: myhdl   File: _toVerilog.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _writeFileHeader(f, fn, ts):
    vars = dict(filename=fn,
                version=myhdl.__version__,
                date=datetime.today().ctime()
                )
    if not toVerilog.no_myhdl_header:
        print(string.Template(myhdl_header).substitute(vars), file=f)
    if toVerilog.header:
        print(string.Template(toVerilog.header).substitute(vars), file=f)
    print(file=f)
    print("`timescale %s" % ts, file=f)
    print(file=f) 
Example 19
Project: myhdl   Author: myhdl   File: _toVHDL.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _writeFileHeader(f, fn):
    vars = dict(filename=fn,
                version=myhdl.__version__,
                date=datetime.today().ctime()
                )
    if toVHDL.header:
        print(string.Template(toVHDL.header).substitute(vars), file=f)
    if not toVHDL.no_myhdl_header:
        print(string.Template(myhdl_header).substitute(vars), file=f)
    print(file=f) 
Example 20
Project: ffplayout-engine   Author: ffplayout   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_date(seek_day):
    """
    get date for correct playlist,
    when seek_day is set:
    check if playlist date must be from yesterday
    """
    d = date.today()
    if seek_day and get_time('full_sec') < _playlist.start:
        yesterday = d - timedelta(1)
        return yesterday.strftime('%Y-%m-%d')
    else:
        return d.strftime('%Y-%m-%d') 
Example 21
Project: toonapilib   Author: costastf   File: tag.py    License: MIT License 5 votes vote down vote up
def _get_changelog(contents, version):
    header = f'{version} ({datetime.today().strftime("%d-%m-%Y")})'
    underline = '-' * len(header)
    return (f'\n\n{header}\n'
            f'{underline}\n\n* ' + '\n* '.join([line for line in contents if line]) + '\n') 
Example 22
Project: slack-countdown   Author: esplorio   File: countdown.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def days_from_christmas():
    """Calculates the number of days between the current date and the next 
    Christmas. Returns the string to displayed.
    """
    currentdate = datetime.now()
    christmas = datetime(datetime.today().year, 12, 25)
    if christmas < currentdate:
        christmas = date(datetime.today().year + 1, 12, 25)
    delta = christmas - currentdate
    days = delta.days
    if days == 1:
        return "%d day from the nearest Christmas" % days
    else:
        return "%d days from the nearest Christmas" % days 
Example 23
Project: slack-countdown   Author: esplorio   File: countdown.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def days_from_date(strdate, business_days):
    """ Returns the number of days between strdate and today. Add one to date
    as date caclulate is relative to time
    """
    currentdate = datetime.today()
    futuredate = datetime.strptime(strdate, '%Y-%m-%d')
    if business_days:
        delta = workdays.networkdays(currentdate, futuredate)
    else:
        delta = (futuredate - currentdate).days + 1
    return delta 
Example 24
Project: plugin.video.emby   Author: MediaBrowser   File: library.py    License: GNU General Public License v3.0 5 votes vote down vote up
def worker_verify(self):

        ''' Wait 60 seconds to verify the item by moving it to the updated queue to
            verify item is still available to user.
            Used for internal deletion--callback takes too long
            Used for parental control--server does not send a new event when item has been blocked.
        '''
        if self.verify_queue.qsize():

            ready = []
            not_ready = []

            while True:

                try:
                    time_set, item_id = self.verify_queue.get(timeout=1)
                except Queue.Empty:
                    break

                if time_set <= datetime.today():
                    ready.append(item_id)
                elif item_id not in list(self.removed_queue.queue):
                    not_ready.append((time_set, item_id,))
                
                self.verify_queue.task_done()

            self.updated(ready)
            map(self.verify_queue.put, not_ready) # re-add items that are not ready yet 
Example 25
Project: plugin.video.emby   Author: MediaBrowser   File: library.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delay_verify(self, data):

        ''' Setup a 1 minute delay for items to be verified.
        '''
        if not data:
            return

        time_set = datetime.today() + timedelta(seconds=60)
        for item in data:
            self.verify_queue.put((time_set, item,))

        LOG.info("---[ verify:%s ]", len(data)) 
Example 26
Project: plugin.video.emby   Author: MediaBrowser   File: webservice.py    License: GNU General Public License v3.0 5 votes vote down vote up
def serve_forever(self):

        ''' Handle one request at a time until stopped.
        '''
        self.stop = False
        self.last = None
        self.last_time = datetime.today()
        self.pending = []
        self.threads = []
        self.queue = Queue.Queue()

        while not self.stop:
            self.handle_request() 
Example 27
Project: seqr   Author: macarthur-lab   File: external_api_2_3_tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mme_match_proxy_no_results(self, mock_post_to_slack, mock_email):
        url = '/api/matchmaker/v1/match'
        request_body = {
            'patient': {
                'id': '12345',
                'contact': {'institution': 'Test Institute', 'href': 'test@test.com', 'name': 'PI'},
                'genomicFeatures': [{'gene': {'id': 'ABCD'}}],
                'features': []
            }}

        self._check_mme_authenticated(url)

        response = self._make_mme_request(url, 'post', content_type='application/json', data=json.dumps(request_body))
        self.assertEqual(response.status_code, 200)
        results = response.json()['results']

        self.assertEqual(len(results), 0)

        incoming_query_q = MatchmakerIncomingQuery.objects.filter(institution='Test Institute')
        self.assertEqual(incoming_query_q.count(), 1)
        self.assertIsNone(incoming_query_q.first().patient_id)

        mock_post_to_slack.assert_called_with(
            'matchmaker_matches',
            """A match request for 12345 came in from Test Institute today.
        The contact information given was: test@test.com.
        We didn't find any individuals in matchbox that matched that query well, *so no results were sent back*."""
        )
        mock_email.assert_not_called()

        # Test receive same request again and notification exception
        mock_post_to_slack.reset_mock()
        mock_post_to_slack.side_effect = Exception('Slack connection error')
        response = self._make_mme_request(url, 'post', content_type='application/json', data=json.dumps(request_body))
        self.assertEqual(response.status_code, 200)
        self.assertListEqual(response.json()['results'], [])
        self.assertEqual(MatchmakerIncomingQuery.objects.filter(institution='Test Institute').count(), 2) 
Example 28
Project: redmine2github   Author: IQSS   File: redmine_issue_downloader.py    License: MIT License 5 votes vote down vote up
def __init__(self, redmine_server, redmine_api_key, project_name_or_identifier, issues_base_directory, **kwargs):
        """
        Constructor

        :param redmine_server: str giving the url of the redmine server.  e.g. https://redmine.myorg.edu/
        :param redmine_api_key: str with a redmine api key
        :param project_name_or_identifier: str or int with either the redmine project id or project identifier
        :param issues_base_directory: str, directory to download the redmine issues in JSON format.  Directory will be crated
        :param specific_tickets_to_download: optional, list of specific ticket numbers to download. e.g. [2215, 2216, etc]
        """
        self.redmine_server = redmine_server
        self.redmine_api_key = redmine_api_key
        self.project_name_or_identifier = project_name_or_identifier
        self.issues_base_directory = issues_base_directory
        self.issue_status = kwargs.get('issue_status', '*') # values 'open', 'closed', '*'

        self.specific_tickets_to_download = kwargs.get('specific_tickets_to_download', None)

        self.redmine_conn = None
        self.redmine_project = None

        self.issue_dirname = join(self.issues_base_directory\
                                ,  datetime.today().strftime(RedmineIssueDownloader.TIME_FORMAT_STRING)\
                                )

        self.setup() 
Example 29
Project: recruit   Author: Frank-qlu   File: test_tools.py    License: Apache License 2.0 5 votes vote down vote up
def test_to_datetime_today(self):
        # See GH#18666
        # Test with one timezone far ahead of UTC and another far behind, so
        # one of these will _almost_ alawys be in a different day from UTC.
        # Unfortunately this test between 12 and 1 AM Samoa time
        # this both of these timezones _and_ UTC will all be in the same day,
        # so this test will not detect the regression introduced in #18666.
        with tm.set_timezone('Pacific/Auckland'):  # 12-13 hours ahead of UTC
            nptoday = np.datetime64('today')\
                .astype('datetime64[ns]').astype(np.int64)
            pdtoday = pd.to_datetime('today')
            pdtoday2 = pd.to_datetime(['today'])[0]

            tstoday = pd.Timestamp('today')
            tstoday2 = pd.Timestamp.today()

            # These should all be equal with infinite perf; this gives
            # a generous margin of 10 seconds
            assert abs(pdtoday.normalize().value - nptoday) < 1e10
            assert abs(pdtoday2.normalize().value - nptoday) < 1e10
            assert abs(pdtoday.value - tstoday.value) < 1e10
            assert abs(pdtoday.value - tstoday2.value) < 1e10

            assert pdtoday.tzinfo is None
            assert pdtoday2.tzinfo is None

        with tm.set_timezone('US/Samoa'):  # 11 hours behind UTC
            nptoday = np.datetime64('today')\
                .astype('datetime64[ns]').astype(np.int64)
            pdtoday = pd.to_datetime('today')
            pdtoday2 = pd.to_datetime(['today'])[0]

            # These should all be equal with infinite perf; this gives
            # a generous margin of 10 seconds
            assert abs(pdtoday.normalize().value - nptoday) < 1e10
            assert abs(pdtoday2.normalize().value - nptoday) < 1e10

            assert pdtoday.tzinfo is None
            assert pdtoday2.tzinfo is None 
Example 30
Project: recruit   Author: Frank-qlu   File: test_tools.py    License: Apache License 2.0 5 votes vote down vote up
def test_to_datetime_today_now_unicode_bytes(self):
        to_datetime([u'now'])
        to_datetime([u'today'])
        if not PY3:
            to_datetime(['now'])
            to_datetime(['today'])