Python datetime.datetime() Examples

The following are code examples for showing how to use datetime.datetime(). 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: Gurux.DLMS.Python   Author: Gurux   File: _GXCommon.py    GNU General Public License v2.0 6 votes vote down vote up
def __getDateTime(cls, value):
        from ..GXDateTime import GXDateTime
        dt = None
        if isinstance(value, (GXDateTime)):
            dt = value
        elif isinstance(value, (datetime, str)):
            dt = GXDateTime(value)
            dt.skip |= DateTimeSkips.MILLISECOND
        else:
            raise ValueError("Invalid date format.")
        return dt

    #
    # Convert date time to DLMS bytes.
    #
    # buff
    # Byte buffer where data is write.
    # value
    # Added value.
    # 
Example 2
Project: Gurux.DLMS.Python   Author: Gurux   File: _GXCommon.py    GNU General Public License v2.0 6 votes vote down vote up
def getGeneralizedTime(cls, dateString):
        year = int(dateString[0:4])
        month = int(dateString[4:6])
        day = int(dateString[6:8])
        hour = int(dateString[8:10])
        minute = int(dateString[10:12])
        #If UTC time.
        if dateString.endsWith("Z"):
            if len(dateString) > 13:
                second = int(dateString[12:14])
            return datetime(year, month, day, hour, minute, second, 0, tzinfo=tzoffset(None, 0))

        if len(dateString) > 17:
            second = int(dateString.substring(12, 14))
        tz = dateString[dateString.length() - 4:]
        return datetime(year, month, day, hour, minute, second, 0, tzinfo=tzoffset(None, tz)) 
Example 3
Project: Gurux.DLMS.Python   Author: Gurux   File: GXDateTime.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, value=None):
        self.extra = DateTimeExtraInfo.NONE
        self.skip = DateTimeSkips.NONE
        self.status = ClockStatus.OK
        self.dayOfWeek = 0
        if isinstance(value, datetime.datetime):
            self.value = value
        elif isinstance(value, str):
            self.value = self.fromString(value)
        elif isinstance(value, GXDateTime):
            self.value = value.value
            self.skip = value.skip
        elif not value:
            self.value = None
        else:
            raise ValueError("Invalid datetime value.") 
Example 4
Project: mpesaviz   Author: savioabuga   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update_records(self, uploaded_file, file_type):
            transactions = []
            for transaction in csv.DictReader(uploaded_file, delimiter=',',):

                # sent transactions
                if file_type == Transaction.TYPES.sent:
                    try:
                        date = time.strptime(transaction['Date'], '%d/%m/%Y %H:%M:%S')
                        date = datetime(*date[:6])
                        transactions.append(Transaction(code=transaction['Code'], date=date, recipient=transaction['Recipient'],
                                                        amount=float(transaction['Amount'].replace(",", "")), type=file_type, phonenumber=PhoneNumber.from_string(transaction['No.'], 'KE')))
                    except NumberParseException:
                        pass

                # received transactions
                if file_type == Transaction.TYPES.received:
                    try:
                        date = time.strptime(transaction['Date'], '%d/%m/%Y %H:%M:%S')
                        date = datetime(*date[:6])
                        transactions.append(Transaction(code=transaction['\xef\xbb\xbf"Code"'], date=date, sent_by=transaction['Sent By'],
                                                        amount=float(transaction['Amount'].replace(",", "")), type=file_type))
                    except NumberParseException:
                        pass

            Transaction.objects.bulk_create(transactions) 
Example 5
Project: mutatest   Author: EvanKepner   File: test_report.py    MIT License 6 votes vote down vote up
def test_get_status_summary(mock_trial_results):
    """Test the status summary based on the trial results."""
    expected = {
        "SURVIVED": 1,
        "DETECTED": 1,
        "ERROR": 1,
        "UNKNOWN": 1,
        "TIMEOUT": 1,
        "TOTAL RUNS": 5,
        "RUN DATETIME": str(datetime(2019, 1, 1)),
    }

    result = get_status_summary(mock_trial_results)
    print(expected)

    assert result == expected 
Example 6
Project: webnull   Author: macrael   File: test_pretty_date.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_delta_tests():
    test_deltas = {
        '5min': { 'delta': datetime.timedelta(minutes=5), 'pretty': '1:40 PM' },
        '5.5min': { 'delta': datetime.timedelta(minutes=5, seconds=32), 'pretty': '1:40 PM' },
        '10min': { 'delta': datetime.timedelta(minutes=10, seconds=2), 'pretty': '1:45 PM' },
        '2hours': { 'delta': datetime.timedelta(hours=2, seconds=4), 'pretty': '3:35 PM' },
        '14hours': { 'delta': datetime.timedelta(hours=14, seconds=2), 'pretty': '3:35 AM' },
        '24hours': { 'delta': datetime.timedelta(hours=24, minutes=10, seconds=2), 'pretty': 'tomorrow at 1:45 PM' },
        '2days': { 'delta': datetime.timedelta(days=2, minutes=10, seconds=2), 'pretty': 'Sunday at 1:45 PM' },
        '6days': { 'delta': datetime.timedelta(days=6, minutes=10, seconds=2), 'pretty': 'Thursday at 1:45 PM' },
        '7days': { 'delta': datetime.timedelta(days=7, minutes=10, seconds=2), 'pretty': 'Friday the 31st at 1:45 PM' },
        '8days': { 'delta': datetime.timedelta(days=8, minutes=10, seconds=2), 'pretty': 'April 1st at 1:45 PM' },
        '8years': { 'delta': datetime.timedelta(weeks=8*52, days=8, minutes=10, seconds=2), 'pretty': 'March 22nd 2025 at 1:45 PM' },
    }

    for label in test_deltas.keys():
        new_test = generate_test(test_deltas[label]['delta'], test_deltas[label]['pretty'])
        test_name = 'test_' + label
        setattr(PrettyDateTests, test_name, new_test) 
Example 7
Project: tom-bot   Author: maartenberg   File: users_plugin.py    MIT License 6 votes vote down vote up
def collect_users_cb(bot, message=None, *args, **kwargs):
    ''' Detect all users and add them to the 'users' table, if not present. Disabled. '''
    LOGGER.info('Beginning user detection.')
    if not bot.known_groups:
        LOGGER.warning('Groups have not been detected, aborting.')
        return
    for group in bot.known_groups:
        for user in group.getParticipants().keys():
            LOGGER.info('User: %s', user)
            bot.cursor.execute('SELECT COUNT(*) FROM users WHERE jid = ?',
                               (user,))
            result = bot.cursor.fetchone()[0]
            if result == 0:
                LOGGER.info('User not yet present in database, adding...')
                currenttime = (datetime.datetime.now() -
                               datetime.datetime(1970, 1, 1)).total_seconds()
                default_timeout = 2 * 60 * 60 # 2 hours
                bot.cursor.execute('''INSERT INTO USERS
                    (jid, lastactive, timeout, admin) VALUES (?, ?, ?, ?)
                ''', (user, currenttime, default_timeout, False))
                LOGGER.info('User added.')
            else:
                LOGGER.info('User present.')
        bot.conn.commit() 
Example 8
Project: shirleytoolate   Author: trobanga   File: cursed.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def on_save(self, button):
        """
        Save and exit.
        """


        vcal = icalendar.Calendar()
        event = icalendar.Event()
        event['uid'] = self.calendar + str(uuid.uuid1())
        # event['dtstart'] = self._datetime_to_ical(datetime.datetime(2016,5,15))
        # event['dtend'] = self._datetime_to_ical(datetime.datetime(2016,5,15))
        event['summary'] = self.msg.edit_text
        vcal.add_component(event)       

        
        logging.debug("EventWidget:on_save:vcal: {}".format(vcal.to_ical()))
        r = self.server.add_event(vcal.to_ical(), self.calendar)
        logging.debug("EventWidget:on_save:add_event: {}".format(r))
        raise urwid.ExitMainLoop() 
Example 9
Project: pyblish-win   Author: pyblish   File: regression.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def CheckConvertTimestampMicrosecondPadding(self):
        """
        http://bugs.python.org/issue14720

        The microsecond parsing of convert_timestamp() should pad with zeros,
        since the microsecond string "456" actually represents "456000".
        """

        con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
        cur = con.cursor()
        cur.execute("CREATE TABLE t (x TIMESTAMP)")

        # Microseconds should be 456000
        cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.456')")

        # Microseconds should be truncated to 123456
        cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.123456789')")

        cur.execute("SELECT * FROM t")
        values = [x[0] for x in cur.fetchall()]

        self.assertEqual(values, [
            datetime.datetime(2012, 4, 4, 15, 6, 0, 456000),
            datetime.datetime(2012, 4, 4, 15, 6, 0, 123456),
        ]) 
Example 10
Project: pyblish-win   Author: pyblish   File: plistlib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def writeValue(self, value):
        if isinstance(value, (str, unicode)):
            self.simpleElement("string", value)
        elif isinstance(value, bool):
            # must switch for bool before int, as bool is a
            # subclass of int...
            if value:
                self.simpleElement("true")
            else:
                self.simpleElement("false")
        elif isinstance(value, (int, long)):
            self.simpleElement("integer", "%d" % value)
        elif isinstance(value, float):
            self.simpleElement("real", repr(value))
        elif isinstance(value, dict):
            self.writeDict(value)
        elif isinstance(value, Data):
            self.writeData(value)
        elif isinstance(value, datetime.datetime):
            self.simpleElement("date", _dateToString(value))
        elif isinstance(value, (tuple, list)):
            self.writeArray(value)
        else:
            raise TypeError("unsuported type: %s" % type(value)) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_pickling_subclass(self):
        # Make sure we can pickle/unpickle an instance of a subclass.
        offset = timedelta(minutes=-300)
        orig = PicklableFixedOffset(offset, 'cookie')
        self.assertIsInstance(orig, tzinfo)
        self.assertTrue(type(orig) is PicklableFixedOffset)
        self.assertEqual(orig.utcoffset(None), offset)
        self.assertEqual(orig.tzname(None), 'cookie')
        for pickler, unpickler, proto in pickle_choices:
            green = pickler.dumps(orig, proto)
            derived = unpickler.loads(green)
            self.assertIsInstance(derived, tzinfo)
            self.assertTrue(type(derived) is PicklableFixedOffset)
            self.assertEqual(derived.utcoffset(None), offset)
            self.assertEqual(derived.tzname(None), 'cookie')

#############################################################################
# Base class for testing a particular aspect of timedelta, time, date and
# datetime comparisons. 
Example 12
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_roundtrip(self):
        for td in (timedelta(days=999999999, hours=23, minutes=59,
                             seconds=59, microseconds=999999),
                   timedelta(days=-999999999),
                   timedelta(days=1, seconds=2, microseconds=3)):

            # Verify td -> string -> td identity.
            s = repr(td)
            self.assertTrue(s.startswith('datetime.'))
            s = s[9:]
            td2 = eval(s)
            self.assertEqual(td, td2)

            # Verify identity via reconstructing from pieces.
            td2 = timedelta(td.days, td.seconds, td.microseconds)
            self.assertEqual(td, td2) 
Example 13
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_argument_passing(self):
        cls = self.theclass
        # A datetime passes itself on, a time passes None.
        class introspective(tzinfo):
            def tzname(self, dt):    return dt and "real" or "none"
            def utcoffset(self, dt):
                return timedelta(minutes = dt and 42 or -42)
            dst = utcoffset

        obj = cls(1, 2, 3, tzinfo=introspective())

        expected = cls is time and "none" or "real"
        self.assertEqual(obj.tzname(), expected)

        expected = timedelta(minutes=(cls is time and -42 or 42))
        self.assertEqual(obj.utcoffset(), expected)
        self.assertEqual(obj.dst(), expected) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_plistlib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _create(self):
        pl = dict(
            aString="Doodah",
            aList=["A", "B", 12, 32.5, [1, 2, 3]],
            aFloat = 0.5,
            anInt = 728,
            aDict=dict(
                anotherString="<hello & 'hi' there!>",
                aUnicodeValue=u'M\xe4ssig, Ma\xdf',
                aTrueValue=True,
                aFalseValue=False,
                deeperDict=dict(a=17, b=32.5, c=[1, 2, "text"]),
            ),
            someData = plistlib.Data("<binary gunk>"),
            someMoreData = plistlib.Data("<lots of binary gunk>\0\1\2\3" * 10),
            nestedData = [plistlib.Data("<lots of binary gunk>\0\1\2\3" * 10)],
            aDate = datetime.datetime(2004, 10, 26, 10, 33, 33),
        )
        pl[u'\xc5benraa'] = "That was a unicode key."
        return pl 
Example 15
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_comparable(self, other):
        if isinstance(other, DateTime):
            s = self.value
            o = other.value
        elif datetime and isinstance(other, datetime.datetime):
            s = self.value
            o = other.strftime("%Y%m%dT%H:%M:%S")
        elif isinstance(other, (str, unicode)):
            s = self.value
            o = other
        elif hasattr(other, "timetuple"):
            s = self.timetuple()
            o = other.timetuple()
        else:
            otype = (hasattr(other, "__class__")
                     and other.__class__.__name__
                     or type(other))
            raise TypeError("Can't compare %s and %s" %
                            (self.__class__.__name__, otype))
        return s, o 
Example 16
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 6 votes vote down vote up
def ensure_datetime(obj):
    """Return the object if it is a datetime-like object

    Parameters
    ----------
    obj : Object to be tested.

    Returns
    -------
    The original object if it is a datetime-like object

    Raises
    ------
    TypeError if `obj` is not datetime-like
    """
    _VALID_TYPES = (str, datetime.datetime, cftime.datetime,
                    np.datetime64)
    if isinstance(obj, _VALID_TYPES):
        return obj
    raise TypeError("datetime-like object required.  "
                    "Type given: {}".format(type(obj))) 
Example 17
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 6 votes vote down vote up
def datetime_or_default(date, default):
    """Return a datetime-like object or a default.

    Parameters
    ----------
    date : `None` or datetime-like object or str
    default : The value to return if `date` is `None`

    Returns
    -------
    `default` if `date` is `None`, otherwise returns the result of
    `utils.times.ensure_datetime(date)`

    """
    if date is None:
        return default
    else:
        return ensure_datetime(date) 
Example 18
Project: aospy   Author: spencerahill   File: test_calc_basic.py    Apache License 2.0 6 votes vote down vote up
def recursive_test_params():
    basic_params = {
        'proj': example_proj,
        'model': example_model,
        'run': example_run,
        'var': condensation_rain,
        'date_range': (datetime.datetime(4, 1, 1),
                       datetime.datetime(6, 12, 31)),
        'intvl_in': 'monthly',
        'dtype_in_time': 'ts'
    }
    recursive_params = basic_params.copy()

    recursive_condensation_rain = Var(
        name='recursive_condensation_rain',
        variables=(precip, convection_rain), func=lambda x, y: x - y,
        def_time=True)
    recursive_params['var'] = recursive_condensation_rain

    yield (basic_params, recursive_params)

    _clean_test_direcs() 
Example 19
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: json.py    Apache License 2.0 6 votes vote down vote up
def default(self, o):
        """Implement this method in a subclass such that it returns a
        serializable object for ``o``, or calls the base implementation (to
        raise a ``TypeError``).

        For example, to support arbitrary iterators, you could implement
        default like this::

            def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                return JSONEncoder.default(self, o)
        """
        if isinstance(o, datetime):
            return http_date(o)
        if isinstance(o, uuid.UUID):
            return str(o)
        if hasattr(o, '__html__'):
            return text_type(o.__html__())
        return _json.JSONEncoder.default(self, o) 
Example 20
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: json.py    Apache License 2.0 6 votes vote down vote up
def default(self, o):
        """Implement this method in a subclass such that it returns a
        serializable object for ``o``, or calls the base implementation (to
        raise a ``TypeError``).

        For example, to support arbitrary iterators, you could implement
        default like this::

            def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                return JSONEncoder.default(self, o)
        """
        if isinstance(o, datetime):
            return http_date(o)
        if isinstance(o, uuid.UUID):
            return str(o)
        if hasattr(o, '__html__'):
            return text_type(o.__html__())
        return _json.JSONEncoder.default(self, o) 
Example 21
Project: kipet   Author: salvadorgarciamunoz   File: ResultsObject.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        """
        A class to store simulation and optimization results.
        """
        # Data series
        self.generated_datetime = datetime.datetime
        self.results_name = None
        self.solver_statistics = {}
        self.Z = None
        self.X = None
        self.Y = None
        self.C = None
        self.S = None
        self.sigma_sq = None
        self.device_variance = None
        self.P = None
        self.dZdt = None
        self.dXdt = None 
Example 22
Project: Gurux.DLMS.Python   Author: Gurux   File: _GXCommon.py    GNU General Public License v2.0 5 votes vote down vote up
def getDLMSDataType(cls, value):
        from ..GXDateTime import GXDateTime
        from ..GXDate import GXDate
        from ..GXTime import GXTime
        if value is None:
            ret = DataType.NONE
        elif isinstance(value, (bytes, bytearray, GXByteBuffer)):
            ret = DataType.OCTET_STRING
        #elif isinstance(value, (Enum,)):
        #    ret = DataType.ENUM
        elif isinstance(value, int):
            ret = DataType.INT32
        elif isinstance(value, GXTime):
            ret = DataType.TIME
        elif isinstance(value, GXDate):
            ret = DataType.DATE
        elif isinstance(value, (datetime, GXDateTime)):
            ret = DataType.DATETIME
        elif isinstance(value, list):
            ret = DataType.ARRAY
        elif isinstance(value, str):
            ret = DataType.STRING
        elif isinstance(value, bool):
            ret = DataType.BOOLEAN
        elif isinstance(value, float):
            ret = DataType.FLOAT32
        else:
            raise ValueError("Invalid value.")
        return ret 
Example 23
Project: Gurux.DLMS.Python   Author: Gurux   File: GXDateTime.py    GNU General Public License v2.0 5 votes vote down vote up
def fromUnixTime(cls, unixTime):
        return GXDateTime(datetime.datetime(unixTime * 1000))

    #
    # Convert date time to Epoch time.
    #
    # @param date
    #            Date and time.
    # Unix time.
    # 
Example 24
Project: jumpserver-python-sdk   Author: jumpserver   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def from_json(cls, json_dict):
        self = cls()
        for k, v in json_dict.items():
            if isinstance(getattr(self, k, None), datetime.datetime) and v:
                try:
                    if len(v.strip().split()) == 2:
                        v += " +0000"
                    v = datetime.datetime.strptime(v, "%Y-%m-%d %H:%M:%S %z")
                except TypeError:
                    pass
            if hasattr(self, k):
                setattr(self, k, v)
        return self 
Example 25
Project: webnull   Author: macrael   File: test_pretty_date.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.now = datetime.datetime(2017, 3, 24, 13, 35, 22) 
Example 26
Project: tom-bot   Author: maartenberg   File: mention_plugin.py    MIT License 5 votes vote down vote up
def update_lastseen_cb(bot, message, *args, **kwargs):
    ''' Updates the user's last seen time in the database. '''
    author = determine_sender(message)
    currenttime = (datetime.datetime.now() - datetime.datetime(1970, 1, 1)).total_seconds()
    LOGGER.debug('Updating %s\'s last seen.', author)
    bot.cursor.execute('UPDATE users SET lastactive = ?, message = ? WHERE jid = ?',
                       (currenttime, message.getBody().decode('utf-8'), author))
    bot.conn.commit() 
Example 27
Project: tom-bot   Author: maartenberg   File: reminder_plugin.py    MIT License 5 votes vote down vote up
def addreminder_cb(bot, message, *args, **kwargs):
    ''' (Hopefully) sends user a message at the given time '''
    body = extract_query(message)
    timespec = body.split()[0]
    try:
        trytime = dateutil.parser.parse(body, parserinfo=datefinder.BPI, fuzzy=True)
    except ValueError:
        trytime = datetime.datetime(1970, 1, 1) # job is dropped if no other date is found
    delta = None
    if timespec in datefinder.DURATION_MARKERS or datefinder.STRICT_CLOCK_REGEX.match(timespec):
        try:
            delta = datetime.datetime.now() + datefinder.find_timedelta(body)
        except ValueError:
            delta = None
    elif timespec in datefinder.CLOCK_MARKERS:
        try:
            trytime = datefinder.find_first_time(body)
        except ValueError:
            LOGGER.error('Cannot find time in "%s"', body)
    if delta:
        deadline = delta
    else:
        deadline = trytime
    if deadline < datetime.datetime.now():
        LOGGER.error('Parsing %s failed, invalid deadline')
        return 'Sorry, limitations prevent parsing that kind of time.'
    LOGGER.debug('Parsed reminder command "%s"', body)
    LOGGER.info('Deadline %s from message "%s".',
                deadline, body)
    reply = 'Reminder set for {}.'.format(deadline)
    replymessage = TextMessageProtocolEntity(
        to=determine_sender(message), body=reply)
    bot.toLower(replymessage)
    bot.scheduler.add_job(
        rpc.remote_send, 'date',
        [body, determine_sender(message)],
        run_date=deadline)
    return 
Example 28
Project: shirleytoolate   Author: trobanga   File: cursed.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _datetime_to_ical(self, dt):
        """
        Converts datetime format to ical format and returns it.
        """
        return icalendar.vDatetime(dt).to_ical() 
Example 29
Project: pyblish-win   Author: pyblish   File: regression.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def CheckColumnNameWithSpaces(self):
        cur = self.con.cursor()
        cur.execute('select 1 as "foo bar [datetime]"')
        self.assertEqual(cur.description[0][0], "foo bar")

        cur.execute('select 1 as "foo baz"')
        self.assertEqual(cur.description[0][0], "foo baz") 
Example 30
Project: pyblish-win   Author: pyblish   File: regression.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def CheckTypeMapUsage(self):
        """
        pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling
        a statement. This test exhibits the problem.
        """
        SELECT = "select * from foo"
        con = sqlite.connect(":memory:",detect_types=sqlite.PARSE_DECLTYPES)
        con.execute("create table foo(bar timestamp)")
        con.execute("insert into foo(bar) values (?)", (datetime.datetime.now(),))
        con.execute(SELECT)
        con.execute("drop table foo")
        con.execute("create table foo(bar integer)")
        con.execute("insert into foo(bar) values (5)")
        con.execute(SELECT) 
Example 31
Project: pyblish-win   Author: pyblish   File: types.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def CheckSqlTimestamp(self):
        # The date functions are only available in SQLite version 3.1 or later
        if sqlite.sqlite_version_info < (3, 1):
            return

        # SQLite's current_timestamp uses UTC time, while datetime.datetime.now() uses local time.
        now = datetime.datetime.now()
        self.cur.execute("insert into test(ts) values (current_timestamp)")
        self.cur.execute("select ts from test")
        ts = self.cur.fetchone()[0]
        self.assertEqual(type(ts), datetime.datetime)
        self.assertEqual(ts.year, now.year) 
Example 32
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def register_adapters_and_converters():
    def adapt_date(val):
        return val.isoformat()

    def adapt_datetime(val):
        return val.isoformat(" ")

    def convert_date(val):
        return datetime.date(*map(int, val.split("-")))

    def convert_timestamp(val):
        datepart, timepart = val.split(" ")
        year, month, day = map(int, datepart.split("-"))
        timepart_full = timepart.split(".")
        hours, minutes, seconds = map(int, timepart_full[0].split(":"))
        if len(timepart_full) == 2:
            microseconds = int('{:0<6.6}'.format(timepart_full[1].decode()))
        else:
            microseconds = 0

        val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds)
        return val


    register_adapter(datetime.date, adapt_date)
    register_adapter(datetime.datetime, adapt_datetime)
    register_converter("date", convert_date)
    register_converter("timestamp", convert_timestamp) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_hash.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_hash_command(self, repr_):
        return 'import datetime; print(hash(%s))' % repr_ 
Example 34
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fraction(self):
        # Test microseconds
        import datetime
        d = datetime.datetime(2012, 12, 20, 12, 34, 56, 78987)
        tup, frac = _strptime._strptime(str(d), format="%Y-%m-%d %H:%M:%S.%f")
        self.assertEqual(frac, d.microsecond) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_constants(self):
        import datetime
        self.assertEqual(datetime.MINYEAR, 1)
        self.assertEqual(datetime.MAXYEAR, 9999)

#############################################################################
# tzinfo tests 
Example 36
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_non_abstractness(self):
        # In order to allow subclasses to get pickled, the C implementation
        # wasn't able to get away with having __init__ raise
        # NotImplementedError.
        useless = tzinfo()
        dt = datetime.max
        self.assertRaises(NotImplementedError, useless.tzname, dt)
        self.assertRaises(NotImplementedError, useless.utcoffset, dt)
        self.assertRaises(NotImplementedError, useless.dst, dt) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_normal(self):
        fo = FixedOffset(3, "Three")
        self.assertIsInstance(fo, tzinfo)
        for dt in datetime.now(), None:
            self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
            self.assertEqual(fo.tzname(dt), "Three")
            self.assertEqual(fo.dst(dt), timedelta(minutes=42)) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        for dt in (self.theclass(1, 2, 3),
                   self.theclass.today()):
            # Verify dt -> string -> date identity.
            s = repr(dt)
            self.assertTrue(s.startswith('datetime.'))
            s = s[9:]
            dt2 = eval(s)
            self.assertEqual(dt, dt2)

            # Verify identity via reconstructing from pieces.
            dt2 = self.theclass(dt.year, dt.month, dt.day)
            self.assertEqual(dt, dt2) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mixed_compare(self):
        our = self.theclass(2000, 4, 5)
        self.assertRaises(TypeError, cmp, our, 1)
        self.assertRaises(TypeError, cmp, 1, our)

        class AnotherDateTimeClass(object):
            def __cmp__(self, other):
                # Return "equal" so calling this can't be confused with
                # compare-by-address (which never says "equal" for distinct
                # objects).
                return 0
            __hash__ = None # Silence Py3k warning

        # This still errors, because date and datetime comparison raise
        # TypeError instead of NotImplemented when they don't know what to
        # do, in order to stop comparison from falling back to the default
        # compare-by-address.
        their = AnotherDateTimeClass()
        self.assertRaises(TypeError, cmp, our, their)
        # Oops:  The next stab raises TypeError in the C implementation,
        # but not in the Python implementation of datetime.  The difference
        # is due to that the Python implementation defines __cmp__ but
        # the C implementation defines tp_richcompare.  This is more pain
        # to fix than it's worth, so commenting out the test.
        # self.assertEqual(cmp(their, our), 0)

        # But date and datetime comparison return NotImplemented instead if the
        # other object has a timetuple attr.  This gives the other object a
        # chance to do the comparison.
        class Comparable(AnotherDateTimeClass):
            def timetuple(self):
                return ()

        their = Comparable()
        self.assertEqual(cmp(our, their), 0)
        self.assertEqual(cmp(their, our), 0)
        self.assertTrue(our == their)
        self.assertTrue(their == our) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
                   self.theclass.now()):
            # Verify dt -> string -> datetime identity.
            s = repr(dt)
            self.assertTrue(s.startswith('datetime.'))
            s = s[9:]
            dt2 = eval(s)
            self.assertEqual(dt, dt2)

            # Verify identity via reconstructing from pieces.
            dt2 = self.theclass(dt.year, dt.month, dt.day,
                                dt.hour, dt.minute, dt.second,
                                dt.microsecond)
            self.assertEqual(dt, dt2) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_more_compare(self):
        # The test_compare() inherited from TestDate covers the error cases.
        # We just want to test lexicographic ordering on the members datetime
        # has that date lacks.
        args = [2000, 11, 29, 20, 58, 16, 999998]
        t1 = self.theclass(*args)
        t2 = self.theclass(*args)
        self.assertTrue(t1 == t2)
        self.assertTrue(t1 <= t2)
        self.assertTrue(t1 >= t2)
        self.assertFalse(t1 != t2)
        self.assertFalse(t1 < t2)
        self.assertFalse(t1 > t2)
        self.assertEqual(cmp(t1, t2), 0)
        self.assertEqual(cmp(t2, t1), 0)

        for i in range(len(args)):
            newargs = args[:]
            newargs[i] = args[i] + 1
            t2 = self.theclass(*newargs)   # this is larger than t1
            self.assertTrue(t1 < t2)
            self.assertTrue(t2 > t1)
            self.assertTrue(t1 <= t2)
            self.assertTrue(t2 >= t1)
            self.assertTrue(t1 != t2)
            self.assertTrue(t2 != t1)
            self.assertFalse(t1 == t2)
            self.assertFalse(t2 == t1)
            self.assertFalse(t1 > t2)
            self.assertFalse(t2 < t1)
            self.assertFalse(t1 >= t2)
            self.assertFalse(t2 <= t1)
            self.assertEqual(cmp(t1, t2), -1)
            self.assertEqual(cmp(t2, t1), 1)


    # A helper for timestamp constructor tests. 
Example 42
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        t = self.theclass(1, 2, 3, 4)

        # Verify t -> string -> time identity.
        s = repr(t)
        self.assertTrue(s.startswith('datetime.'))
        s = s[9:]
        t2 = eval(s)
        self.assertEqual(t, t2)

        # Verify identity via reconstructing from pieces.
        t2 = self.theclass(t.hour, t.minute, t.second,
                           t.microsecond)
        self.assertEqual(t, t2) 
Example 43
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        name = 'datetime.' + self.theclass.__name__
        self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
                         "%s(1, 2, 3, 4)" % name)
        self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
                         "%s(10, 2, 3, 4000)" % name)
        self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
                         "%s(0, 2, 3, 400000)" % name)
        self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
                         "%s(12, 2, 3)" % name)
        self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
                         "%s(23, 15)" % name) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_utc_offset_out_of_bounds(self):
        class Edgy(tzinfo):
            def __init__(self, offset):
                self.offset = timedelta(minutes=offset)
            def utcoffset(self, dt):
                return self.offset

        cls = self.theclass
        for offset, legit in ((-1440, False),
                              (-1439, True),
                              (1439, True),
                              (1440, False)):
            if cls is time:
                t = cls(1, 2, 3, tzinfo=Edgy(offset))
            elif cls is datetime:
                t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
            else:
                assert 0, "impossible"
            if legit:
                aofs = abs(offset)
                h, m = divmod(aofs, 60)
                tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
                if isinstance(t, datetime):
                    t = t.timetz()
                self.assertEqual(str(t), "01:02:03" + tag)
            else:
                self.assertRaises(ValueError, str, t) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_subclass_timetz(self):

        class C(self.theclass):
            theAnswer = 42

            def __new__(cls, *args, **kws):
                temp = kws.copy()
                extra = temp.pop('extra')
                result = self.theclass.__new__(cls, *args, **temp)
                result.extra = extra
                return result

            def newmeth(self, start):
                return start + self.hour + self.second

        args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1)

        dt1 = self.theclass(*args)
        dt2 = C(*args, **{'extra': 7})

        self.assertEqual(dt2.__class__, C)
        self.assertEqual(dt2.theAnswer, 42)
        self.assertEqual(dt2.extra, 7)
        self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
        self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)


# Testing datetime objects with a non-None tzinfo. 
Example 46
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_extreme_hashes(self):
        # If an attempt is made to hash these via subtracting the offset
        # then hashing a datetime object, OverflowError results.  The
        # Python implementation used to blow up here.
        t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
        hash(t)
        t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
                          tzinfo=FixedOffset(-1439, ""))
        hash(t)

        # OTOH, an OOB offset should blow up.
        t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
        self.assertRaises(ValueError, hash, t) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_zones(self):
        est = FixedOffset(-300, "EST")
        utc = FixedOffset(0, "UTC")
        met = FixedOffset(60, "MET")
        t1 = datetime(2002, 3, 19,  7, 47, tzinfo=est)
        t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
        t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
        self.assertEqual(t1.tzinfo, est)
        self.assertEqual(t2.tzinfo, utc)
        self.assertEqual(t3.tzinfo, met)
        self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
        self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
        self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
        self.assertEqual(t1.tzname(), "EST")
        self.assertEqual(t2.tzname(), "UTC")
        self.assertEqual(t3.tzname(), "MET")
        self.assertEqual(hash(t1), hash(t2))
        self.assertEqual(hash(t1), hash(t3))
        self.assertEqual(hash(t2), hash(t3))
        self.assertEqual(t1, t2)
        self.assertEqual(t1, t3)
        self.assertEqual(t2, t3)
        self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
        self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
        self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
        d = 'datetime.datetime(2002, 3, 19, '
        self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
        self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
        self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)") 
Example 48
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_now(self):
        meth = self.theclass.now
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(off42)
        again = meth(tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, 16)
        self.assertRaises(TypeError, meth, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, off42, off42)

        # We don't know which time zone we're in, and don't have a tzinfo
        # class to represent it, so seeing whether a tz argument actually
        # does a conversion is tricky.
        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
        utc = FixedOffset(0, "utc", 0)
        for dummy in range(3):
            now = datetime.now(weirdtz)
            self.assertIs(now.tzinfo, weirdtz)
            utcnow = datetime.utcnow().replace(tzinfo=utc)
            now2 = utcnow.astimezone(weirdtz)
            if abs(now - now2) < timedelta(seconds=30):
                break
            # Else the code is broken, or more than 30 seconds passed between
            # calls; assuming the latter, just try again.
        else:
            # Three strikes and we're out.
            self.fail("utcnow(), now(tz), or astimezone() may be broken") 
Example 49
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None)) 
Example 50
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_timetuple(self):
        # TestDateTime tested most of this.  datetime adds a twist to the
        # DST flag.
        class DST(tzinfo):
            def __init__(self, dstvalue):
                if isinstance(dstvalue, int):
                    dstvalue = timedelta(minutes=dstvalue)
                self.dstvalue = dstvalue
            def dst(self, dt):
                return self.dstvalue

        cls = self.theclass
        for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
            d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
            t = d.timetuple()
            self.assertEqual(1, t.tm_year)
            self.assertEqual(1, t.tm_mon)
            self.assertEqual(1, t.tm_mday)
            self.assertEqual(10, t.tm_hour)
            self.assertEqual(20, t.tm_min)
            self.assertEqual(30, t.tm_sec)
            self.assertEqual(0, t.tm_wday)
            self.assertEqual(1, t.tm_yday)
            self.assertEqual(flag, t.tm_isdst)

        # dst() returns wrong type.
        self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)

        # dst() at the edge.
        self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
        self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)

        # dst() out of range.
        self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
        self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple) 
Example 51
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mixed_compare(self):
        t1 = datetime(1, 2, 3, 4, 5, 6, 7)
        t2 = datetime(1, 2, 3, 4, 5, 6, 7)
        self.assertEqual(t1, t2)
        t2 = t2.replace(tzinfo=None)
        self.assertEqual(t1, t2)
        t2 = t2.replace(tzinfo=FixedOffset(None, ""))
        self.assertEqual(t1, t2)
        t2 = t2.replace(tzinfo=FixedOffset(0, ""))
        self.assertRaises(TypeError, lambda: t1 == t2)

        # In datetime w/ identical tzinfo objects, utcoffset is ignored.
        class Varies(tzinfo):
            def __init__(self):
                self.offset = timedelta(minutes=22)
            def utcoffset(self, t):
                self.offset += timedelta(minutes=1)
                return self.offset

        v = Varies()
        t1 = t2.replace(tzinfo=v)
        t2 = t2.replace(tzinfo=v)
        self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
        self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
        self.assertEqual(t1, t2)

        # But if they're not identical, it isn't ignored.
        t2 = t2.replace(tzinfo=Varies())
        self.assertTrue(t1 < t2)  # t1's offset counter still going up 
Example 52
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_dump_bare_datetime(self):
        # This checks that an unwrapped datetime.date object can be handled
        # by the marshalling code.  This can't be done via test_dump_load()
        # since with use_datetime set to 1 the unmarshaller would create
        # datetime objects for the 'datetime[123]' keys as well
        dt = datetime.datetime(2005, 02, 10, 11, 41, 23)
        s = xmlrpclib.dumps((dt,))
        (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
        self.assertEqual(newdt, dt)
        self.assertEqual(m, None)

        (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
        self.assertEqual(newdt, xmlrpclib.DateTime('20050210T11:41:23')) 
Example 53
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_datetime_before_1900(self):
        # same as before but with a date before 1900
        dt = datetime.datetime(1, 02, 10, 11, 41, 23)
        s = xmlrpclib.dumps((dt,))
        (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
        self.assertEqual(newdt, dt)
        self.assertEqual(m, None)

        (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
        self.assertEqual(newdt, xmlrpclib.DateTime('00010210T11:41:23')) 
Example 54
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cmp_datetime_DateTime(self):
        now = datetime.datetime.now()
        dt = xmlrpclib.DateTime(now.timetuple())
        self.assertTrue(dt == now)
        self.assertTrue(now == dt)
        then = now + datetime.timedelta(seconds=4)
        self.assertTrue(then >= dt)
        self.assertTrue(dt < then) 
Example 55
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_datetime_datetime(self):
        d = datetime.datetime(2007,1,2,3,4,5)
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t), '20070102T03:04:05') 
Example 56
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_decode(self):
        d = ' 20070908T07:11:13  '
        t1 = xmlrpclib.DateTime()
        t1.decode(d)
        tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
        self.assertEqual(t1, tref)

        t2 = xmlrpclib._datetime(d)
        self.assertEqual(t1, tref) 
Example 57
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _strftime(value):
    if datetime:
        if isinstance(value, datetime.datetime):
            return "%04d%02d%02dT%02d:%02d:%02d" % (
                value.year, value.month, value.day,
                value.hour, value.minute, value.second)

    if not isinstance(value, (TupleType, time.struct_time)):
        if value == 0:
            value = time.time()
        value = time.localtime(value)

    return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] 
Example 58
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _datetime_type(data):
    t = time.strptime(data, "%Y%m%dT%H:%M:%S")
    return datetime.datetime(*tuple(t)[:6])

##
# Wrapper for binary data.  This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data. 
Example 59
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, use_datetime=0):
        self._type = None
        self._stack = []
        self._marks = []
        self._data = []
        self._methodname = None
        self._encoding = "utf-8"
        self.append = self._stack.append
        self._use_datetime = use_datetime
        if use_datetime and not datetime:
            raise ValueError, "the datetime module is not available" 
Example 60
Project: pygis   Author: giswqs   File: zipfile.py    MIT License 5 votes vote down vote up
def read_zipfile(file_name):
    # opening the zip file in READ mode 
    with ZipFile(file_name, 'r') as zip: 
        for info in zip.infolist(): 
            print(info.filename) 
            print('\tModified:\t' + str(datetime.datetime(*info.date_time))) 
            print('\tSystem:\t\t' + str(info.create_system) + '(0 = Windows, 3 = Unix)') 
            print('\tZIP version:\t' + str(info.create_version)) 
            print('\tCompressed:\t' + str(info.compress_size) + ' bytes') 
            print('\tUncompressed:\t' + str(info.file_size) + ' bytes') 


# Extracting a zip file 
Example 61
Project: xadmin_bugfix   Author: vip68   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, Promise):
            return force_text(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 62
Project: xadmin_bugfix   Author: vip68   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 63
Project: xadmin_bugfix   Author: vip68   File: models.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 64
Project: xadmin_bugfix   Author: vip68   File: chart.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 65
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 66
Project: backtrader-cn   Author: pandalibin   File: test_datas_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def _test_parse_data(self):
        date_string = '2017-01-01'
        parsed_date = bdu.Utils.parse_date(date_string)

        self.assertEqual(parsed_date, dt.datetime(2017, 1, 1)) 
Example 67
Project: rail-line-animation-toolkit   Author: ZHZHH-Arezrh5100   File: query_schedule_12306.py    GNU General Public License v3.0 5 votes vote down vote up
def str2time(time_string):
    t = time.strptime(time_string, '%H:%M')
    return datetime.datetime(year=2000, month=1, day=1, hour=t.tm_hour, minute=t.tm_min)


# transfer time to string, use 3 ~ 26 hour one day 
Example 68
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 5 votes vote down vote up
def apply_time_offset(time, years=0, months=0, days=0, hours=0):
    """Apply a specified offset to the given time array.

    This is useful for GFDL model output of instantaneous values.  For example,
    3 hourly data postprocessed to netCDF files spanning 1 year each will
    actually have time values that are offset by 3 hours, such that the first
    value is for 1 Jan 03:00 and the last value is 1 Jan 00:00 of the
    subsequent year.  This causes problems in xarray, e.g. when trying to group
    by month.  It is resolved by manually subtracting off those three hours,
    such that the dates span from 1 Jan 00:00 to 31 Dec 21:00 as desired.

    Parameters
    ----------
    time : xarray.DataArray representing a timeseries
    years, months, days, hours : int, optional
        The number of years, months, days, and hours, respectively, to offset
        the time array by.  Positive values move the times later.

    Returns
    -------
    pandas.DatetimeIndex

    Examples
    --------
    Case of a length-1 input time array:

    >>> times = xr.DataArray(datetime.datetime(1899, 12, 31, 21))
    >>> apply_time_offset(times)
    Timestamp('1900-01-01 00:00:00')

    Case of input time array with length greater than one:

    >>> times = xr.DataArray([datetime.datetime(1899, 12, 31, 21),
    ...                       datetime.datetime(1899, 1, 31, 21)])
    >>> apply_time_offset(times) # doctest: +NORMALIZE_WHITESPACE
    DatetimeIndex(['1900-01-01', '1899-02-01'], dtype='datetime64[ns]',
                  freq=None)
    """
    return (pd.to_datetime(time.values) +
            pd.DateOffset(years=years, months=months, days=days, hours=hours)) 
Example 69
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 5 votes vote down vote up
def average_time_bounds(ds):
    """Return the average of each set of time bounds in the Dataset.

    Useful for creating a new time array to replace the Dataset's native time
    array, in the case that the latter matches either the start or end bounds.
    This can cause errors in grouping (akin to an off-by-one error) if the
    timesteps span e.g. one full month each.  Note that the Dataset's times
    must not have already undergone "CF decoding", wherein they are converted
    from floats using the 'units' attribute into datetime objects.

    Parameters
    ----------
    ds : xarray.Dataset
        A Dataset containing a time bounds array with name matching
        internal_names.TIME_BOUNDS_STR.  This time bounds array must have two
        dimensions, one of which's coordinates is the Dataset's time array, and
        the other is length-2.

    Returns
    -------
    xarray.DataArray
        The mean of the start and end times of each timestep in the original
        Dataset.

    Raises
    ------
    ValueError
        If the time bounds array doesn't match the shape specified above.

    """
    bounds = ds[TIME_BOUNDS_STR]
    new_times = bounds.mean(dim=BOUNDS_STR, keep_attrs=True)
    new_times = new_times.drop_vars(TIME_STR).rename(TIME_STR)
    new_times[TIME_STR] = new_times
    return new_times 
Example 70
Project: aospy   Author: spencerahill   File: test_utils_times.py    Apache License 2.0 5 votes vote down vote up
def test_apply_time_offset():
    start = datetime.datetime(1900, 5, 10)
    years, months, days, hours = -2, 1, 7, 3
    # test lengths 0, 1, and >1 of input time array
    for periods in range(3):
        times = pd.date_range(start=start, freq='M', periods=periods)
        times = pd.to_datetime(times.values)  # Workaround for pandas bug
        actual = apply_time_offset(xr.DataArray(times), years=years,
                                   months=months, days=days, hours=hours)
        desired = (times + pd.DateOffset(
            years=years, months=months, days=days, hours=hours
        ))
        assert actual.identical(desired) 
Example 71
Project: aospy   Author: spencerahill   File: test_data_loader.py    Apache License 2.0 5 votes vote down vote up
def test_overriding_constructor(gfdl_data_loader, ds_with_time_bounds):
    new = GFDLDataLoader(gfdl_data_loader,
                         data_direc=os.path.join('.', 'a'))
    assert new.data_direc == os.path.join('.', 'a')
    assert new.data_dur == gfdl_data_loader.data_dur
    assert new.data_start_date == gfdl_data_loader.data_start_date
    assert new.data_end_date == gfdl_data_loader.data_end_date
    assert new.preprocess_func == gfdl_data_loader.preprocess_func
    assert new.upcast_float32 == gfdl_data_loader.upcast_float32

    new = GFDLDataLoader(gfdl_data_loader, data_dur=8)
    assert new.data_dur == 8

    new = GFDLDataLoader(gfdl_data_loader,
                         data_start_date=datetime.datetime(2001, 1, 1))
    assert new.data_start_date == datetime.datetime(2001, 1, 1)

    new = GFDLDataLoader(gfdl_data_loader,
                         data_end_date=datetime.datetime(2003, 12, 31))
    assert new.data_end_date == datetime.datetime(2003, 12, 31)

    new = GFDLDataLoader(gfdl_data_loader, preprocess_func=lambda ds: ds)
    xr.testing.assert_identical(new.preprocess_func(ds_with_time_bounds),
                                ds_with_time_bounds)

    new = GFDLDataLoader(gfdl_data_loader, upcast_float32=True)
    assert new.upcast_float32

    new = GFDLDataLoader(gfdl_data_loader, data_vars='all')
    assert new.data_vars == 'all'

    new = GFDLDataLoader(gfdl_data_loader, coords='all')
    assert new.coords == 'all' 
Example 72
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _internal.py    Apache License 2.0 5 votes vote down vote up
def _date_to_unix(arg):
    """Converts a timetuple, integer or datetime object into the seconds from
    epoch in utc.
    """
    if isinstance(arg, datetime):
        arg = arg.utctimetuple()
    elif isinstance(arg, (int, long, float)):
        return int(arg)
    year, month, day, hour, minute, second = arg[:6]
    days = date(year, month, 1).toordinal() - _epoch_ord + day - 1
    hours = days * 24 + hour
    minutes = hours * 60 + minute
    seconds = minutes * 60 + second
    return seconds 
Example 73
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _internal.py    Apache License 2.0 5 votes vote down vote up
def _date_to_unix(arg):
    """Converts a timetuple, integer or datetime object into the seconds from
    epoch in utc.
    """
    if isinstance(arg, datetime):
        arg = arg.utctimetuple()
    elif isinstance(arg, (int, long, float)):
        return int(arg)
    year, month, day, hour, minute, second = arg[:6]
    days = date(year, month, 1).toordinal() - _epoch_ord + day - 1
    hours = days * 24 + hour
    minutes = hours * 60 + minute
    seconds = minutes * 60 + second
    return seconds 
Example 74
Project: Gurux.DLMS.Python   Author: Gurux   File: _GXCommon.py    GNU General Public License v2.0 4 votes vote down vote up
def getTime(cls, buff, info):
        # pylint: disable=broad-except
        from ..GXTime import GXTime
        value = None
        if len(buff) - buff.position < 4:
            #  If there is not enough data available.
            info.complete = (False)
            return None
        str_ = None
        if info.xml:
            str_ = buff.toHex(False, buff.position, 4)
        try:
            value = GXTime(None)
            #  Get time.
            hour = buff.getUInt8()
            if hour == 0xFF:
                hour = 0
                value.skip |= DateTimeSkips.HOUR
            minute = buff.getUInt8()
            if minute == 0xFF:
                minute = 0
                value.skip |= DateTimeSkips.MINUTE
            second = buff.getUInt8()
            if second == 0xFF:
                second = 0
                value.skip |= DateTimeSkips.SECOND
            ms = buff.getUInt8()
            if ms != 0xFF:
                ms *= 10
            else:
                ms = 0
                value.skip |= DateTimeSkips.MILLISECOND
            value.value = datetime(1900, 1, 1, hour, minute, second, ms)
        except Exception as ex:
            if info.xml is None:
                raise ex
        if info.xml:
            if value:
                info.xml.appendComment(str(value))
            info.xml.appendLine(info.xml.getDataType(info.type_), None, str_)
        return value

    #
    # Get date from DLMS data.
    #
    # buff
    # Received DLMS data.
    # info
    # Data info.
    # Parsed date.
    # 
Example 75
Project: tom-bot   Author: maartenberg   File: mention_plugin.py    MIT License 4 votes vote down vote up
def mention_handler_cb(bot, message, *args, **kwargs):
    '''
    Scans message text for @mentions and notifies user if appropriate.
    '''
    mentioned_sent = []
    for nick in MENTION_REGEX.findall(message.getBody()):
        LOGGER.debug('Nick detected: %s', nick)

        # Who sent the message?
        senderjid = determine_sender(message)
        LOGGER.debug('Resolving sender %s', senderjid)
        try:
            sendername = jid_to_nick(bot, senderjid)
            LOGGER.debug('Sendernick %s', sendername)
        except KeyError:
            sendername = senderjid
            LOGGER.debug('Could not find jid %s', senderjid)

        # Who was mentioned?
        try:
            targetjid = nick_to_jid(bot, nick)
            LOGGER.debug('Targetjid %s', targetjid)
        except KeyError as ex:
            # Some nick that is unknown, pass
            LOGGER.debug('Could not resolve nick %s', nick)
            LOGGER.debug('Exception %s', ex)
            continue

        if targetjid not in mentioned_sent:
            # Check timeout
            t_info = get_jid_timeout(bot, targetjid)
            currenttime = (datetime.datetime.now() - datetime.datetime(
                1970, 1, 1)).total_seconds()
            if currenttime < (t_info[1] + t_info[0]) and message.participant:
                # Do not send DM if recipient has not timed out yet
                continue

            # Send mention notification: [author]: [body]
            entity = TextMessageProtocolEntity('{}: {}'.format(
                sendername, message.getBody()), to=targetjid)
            bot.toLower(entity)
            LOGGER.debug('Sent mention with content %s to %s', message.getBody(), targetjid)
            mentioned_sent.append(targetjid)
        else:
            LOGGER.debug('Detected duplicate nick %s, skipping.', targetjid) 
Example 76
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_computations(self):
        a = self.theclass(2002, 1, 31)
        b = self.theclass(1956, 1, 31)
        diff = a-b
        self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
        self.assertEqual(diff.seconds, 0)
        self.assertEqual(diff.microseconds, 0)
        a = self.theclass(2002, 3, 2, 17, 6)
        millisec = timedelta(0, 0, 1000)
        hour = timedelta(0, 3600)
        day = timedelta(1)
        week = timedelta(7)
        self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
        self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
        self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
        self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
        self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
        self.assertEqual(a - hour, a + -hour)
        self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
        self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
        self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
        self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
        self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
        self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
        self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
        self.assertEqual((a + week) - a, week)
        self.assertEqual((a + day) - a, day)
        self.assertEqual((a + hour) - a, hour)
        self.assertEqual((a + millisec) - a, millisec)
        self.assertEqual((a - week) - a, -week)
        self.assertEqual((a - day) - a, -day)
        self.assertEqual((a - hour) - a, -hour)
        self.assertEqual((a - millisec) - a, -millisec)
        self.assertEqual(a - (a + week), -week)
        self.assertEqual(a - (a + day), -day)
        self.assertEqual(a - (a + hour), -hour)
        self.assertEqual(a - (a + millisec), -millisec)
        self.assertEqual(a - (a - week), week)
        self.assertEqual(a - (a - day), day)
        self.assertEqual(a - (a - hour), hour)
        self.assertEqual(a - (a - millisec), millisec)
        self.assertEqual(a + (week + day + hour + millisec),
                         self.theclass(2002, 3, 10, 18, 6, 0, 1000))
        self.assertEqual(a + (week + day + hour + millisec),
                         (((a + week) + day) + hour) + millisec)
        self.assertEqual(a - (week + day + hour + millisec),
                         self.theclass(2002, 2, 22, 16, 5, 59, 999000))
        self.assertEqual(a - (week + day + hour + millisec),
                         (((a - week) - day) - hour) - millisec)
        # Add/sub ints, longs, floats should be illegal
        for i in 1, 1L, 1.0:
            self.assertRaises(TypeError, lambda: a+i)
            self.assertRaises(TypeError, lambda: a-i)
            self.assertRaises(TypeError, lambda: i+a)
            self.assertRaises(TypeError, lambda: i-a)

        # delta - datetime is senseless. 
Example 77
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_tz_aware_arithmetic(self):
        import random

        now = self.theclass.now()
        tz55 = FixedOffset(-330, "west 5:30")
        timeaware = now.time().replace(tzinfo=tz55)
        nowaware = self.theclass.combine(now.date(), timeaware)
        self.assertIs(nowaware.tzinfo, tz55)
        self.assertEqual(nowaware.timetz(), timeaware)

        # Can't mix aware and non-aware.
        self.assertRaises(TypeError, lambda: now - nowaware)
        self.assertRaises(TypeError, lambda: nowaware - now)

        # And adding datetime's doesn't make sense, aware or not.
        self.assertRaises(TypeError, lambda: now + nowaware)
        self.assertRaises(TypeError, lambda: nowaware + now)
        self.assertRaises(TypeError, lambda: nowaware + nowaware)

        # Subtracting should yield 0.
        self.assertEqual(now - now, timedelta(0))
        self.assertEqual(nowaware - nowaware, timedelta(0))

        # Adding a delta should preserve tzinfo.
        delta = timedelta(weeks=1, minutes=12, microseconds=5678)
        nowawareplus = nowaware + delta
        self.assertIs(nowaware.tzinfo, tz55)
        nowawareplus2 = delta + nowaware
        self.assertIs(nowawareplus2.tzinfo, tz55)
        self.assertEqual(nowawareplus, nowawareplus2)

        # that - delta should be what we started with, and that - what we
        # started with should be delta.
        diff = nowawareplus - delta
        self.assertIs(diff.tzinfo, tz55)
        self.assertEqual(nowaware, diff)
        self.assertRaises(TypeError, lambda: delta - nowawareplus)
        self.assertEqual(nowawareplus - nowaware, delta)

        # Make up a random timezone.
        tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
        # Attach it to nowawareplus.
        nowawareplus = nowawareplus.replace(tzinfo=tzr)
        self.assertIs(nowawareplus.tzinfo, tzr)
        # Make sure the difference takes the timezone adjustments into account.
        got = nowaware - nowawareplus
        # Expected:  (nowaware base - nowaware offset) -
        #            (nowawareplus base - nowawareplus offset) =
        #            (nowaware base - nowawareplus base) +
        #            (nowawareplus offset - nowaware offset) =
        #            -delta + nowawareplus offset - nowaware offset
        expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
        self.assertEqual(got, expected)

        # Try max possible difference.
        min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
        max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
                            tzinfo=FixedOffset(-1439, "max"))
        maxdiff = max - min
        self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
                                  timedelta(minutes=2*1439)) 
Example 78
Project: rail-line-animation-toolkit   Author: ZHZHH-Arezrh5100   File: query_schedule_12306.py    GNU General Public License v3.0 4 votes vote down vote up
def query_single_train(train_name='G1', date=None, default_params=None):

    # search train No. by train name (根据车次查车次编号)
    # query JSON data from 12306 (下载JSON数据)
    url_train = r'https://search.12306.cn/search/v1/train/search'  # the url may be changed, check the latest on 12306.cn
    parameter_dict = {'keyword': train_name,
                      'date': (datetime.date.today() + datetime.timedelta(days=1)).strftime(
        '%Y%m%d') if date is None else date.replace('-', '')}
    req = request.Request(url='%s%s%s' % (url_train, '?', parse.urlencode(parameter_dict)))
    try:
        train_res = request.urlopen(req)
    except (HTTPError, URLError):
        print('Failed to get train code from 12306!')
        return None
    else:
        train_str = train_res.read()
    # decode JSON to Object (JSON转为对象)
    try:
        train_json = json.loads(train_str)
    except json.JSONDecodeError:
        print('Failed to decode train information from 12306!')
        # print(train_str.decode('utf-8'))
        return None
    # validate train name (验证查到的车次)
    train_no = None
    if isinstance(train_json, dict):
        if 'data' in train_json:
            if isinstance(train_json['data'], list):
                for train_data in train_json['data']:
                    if isinstance(train_data, dict):
                        if ('station_train_code' in train_data) and ('train_no' in train_data):
                            if train_data['station_train_code'] == train_name:
                                train_no = train_data['train_no']
                                break
    if train_no is None:
        print('Train {0} not found!'.format(train_name))
        # print(train_json)
        return None
    
    # train info (整理列车信息)
    train = {'train_no': train_no, 'train_name': train_name, 'from': 'XXX', 'to': 'XXX', 'destination': 'XXX'}
    train['train_class'] = train_name[0] if train_name[0].isalpha() else '0'

    # set other params (设置其他参数)
    if default_params is None:
        default_params = ['1', '1', 'D']
    train['icon_id'] = default_params[0]
    train['class_color'] = train['train_class']
    train['destination_color'] = 'TO_OTHER_LINES'

    # query stop information (查询停站时刻信息)
    print('Querying stops info...')
    csv_df = query_stops_of(train, date, default_params[1], default_params[2], 1)
    
    return csv_df


# query the information of trains between two stations (查询站间列车信息) 
Example 79
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 4 votes vote down vote up
def _assert_has_data_for_time(da, start_date, end_date):
    """Check to make sure data is in Dataset for the given time range.

    Parameters
    ----------
    da : DataArray
         DataArray with a time variable
    start_date : datetime-like object or str
         start date
    end_date : datetime-like object or str
         end date

    Raises
    ------
    AssertionError
         If the time range is not within the time range of the DataArray

    """
    if isinstance(start_date, str) and isinstance(end_date, str):
        logging.warning(
            'When using strings to specify start and end dates, the check '
            'to determine if data exists for the full extent of the desired '
            'interval is not implemented.  Therefore it is possible that '
            'you are doing a calculation for a lesser interval than you '
            'specified.  If you would like this check to occur, use explicit '
            'datetime-like objects for bounds instead.')
        return

    if RAW_START_DATE_STR in da.coords:
        with warnings.catch_warnings(record=True):
            da_start = da[RAW_START_DATE_STR].values
            da_end = da[RAW_END_DATE_STR].values
    else:
        times = da.time.isel(**{TIME_STR: [0, -1]})
        da_start, da_end = times.values

    message = ('Data does not exist for requested time range: {0} to {1};'
               ' found data from time range: {2} to {3}.')
    # Add tolerance of one second, due to precision of cftime.datetimes
    tol = datetime.timedelta(seconds=1)
    if isinstance(da_start, np.datetime64):
        tol = np.timedelta64(tol, 'ns')
    range_exists = ((da_start - tol) <= start_date and
                    (da_end + tol) >= end_date)
    assert (range_exists), message.format(start_date, end_date,
                                          da_start, da_end) 
Example 80
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 4 votes vote down vote up
def maybe_convert_to_index_date_type(index, date):
    """Convert a datetime-like object to the index's date type.

    Datetime indexing in xarray can be done using either a pandas
    DatetimeIndex or a CFTimeIndex.  Both support partial-datetime string
    indexing regardless of the calendar type of the underlying data;
    therefore if a string is passed as a date, we return it unchanged.  If a
    datetime-like object is provided, it will be converted to the underlying
    date type of the index.  For a DatetimeIndex that is np.datetime64; for a
    CFTimeIndex that is an object of type cftime.datetime specific to the
    calendar used.

    Parameters
    ----------
    index : pd.Index
        Input time index
    date : datetime-like object or str
        Input datetime

    Returns
    -------
    date of the type appropriate for the time index of the Dataset
    """
    if isinstance(date, str):
        return date

    if isinstance(index, pd.DatetimeIndex):
        if isinstance(date, np.datetime64):
            return date
        else:
            return np.datetime64(str(date))
    else:
        date_type = index.date_type
        if isinstance(date, date_type):
            return date
        else:
            if isinstance(date, np.datetime64):
                # Convert to datetime.date or datetime.datetime object
                date = date.item()

            if isinstance(date, datetime.date):
                # Convert to a datetime.datetime object
                date = datetime.datetime.combine(
                    date, datetime.datetime.min.time())

            return date_type(date.year, date.month, date.day, date.hour,
                             date.minute, date.second, date.microsecond)