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)