How to use the datetime.datetime function in DateTime

To help you get started, we’ve selected a few DateTime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github elastic / curator / test / unit / test_utils.py View on Github external
def test_weeks_single_iso(self):
        unit = 'weeks'
        range_from = -1
        range_to = -1
        epoch = curator.datetime_to_epoch(datetime(2017,  4,  3, 22, 50, 17))
        start = curator.datetime_to_epoch(datetime(2017,  3, 27,  0,  0,  0))
        end   = curator.datetime_to_epoch(datetime(2017,  4,  2, 23, 59, 59))
        self.assertEqual((start,end), 
            curator.date_range(unit, range_from, range_to, epoch=epoch, 
                week_starts_on='monday')
        )
github coleifer / peewee / playhouse / tests_dataset.py View on Github external
for i in range(1, 4):
            note.insert(
                content='note %s' % i,
                timestamp=datetime.date(2014, 1, i),
                user='charlie')

        notes = sorted(note.all(), key=operator.itemgetter('id'))
        self.assertEqual(notes[0], {
            'content': 'note 1',
            'id': 1,
            'timestamp': datetime.datetime(2014, 1, 1),
            'user': 'charlie'})
        self.assertEqual(notes[-1], {
            'content': 'note 3',
            'id': 3,
            'timestamp': datetime.datetime(2014, 1, 3),
            'user': 'charlie'})

        user.insert(username='mickey')
        note.update(user='mickey', id=3, columns=['id'])

        self.assertEqual(note.find(user='charlie').count(), 2)
        self.assertEqual(note.find(user='mickey').count(), 1)

        category = self.dataset['category']
        category.insert(name='c1')
        c1 = category.find_one(name='c1')
        self.assertEqual(c1, {'id': 1, 'name': 'c1', 'parent': None})

        category.insert(name='c2', parent=1)
        c2 = category.find_one(parent=1)
        self.assertEqual(c2, {'id': 2, 'name': 'c2', 'parent': 1})
github geopython / pywps / pywps / dblog.py View on Github external
def log_request(uuid, request):
    """Write OGC WPS request (only the necessary parts) to database logging
    system
    """

    pid = os.getpid()
    operation = request.operation
    version = request.version
    time_start = datetime.datetime.now()
    identifier = _get_identifier(request)

    session = get_session()
    request = ProcessInstance(
        uuid=str(uuid), pid=pid, operation=operation, version=version,
        time_start=time_start, identifier=identifier)

    session.add(request)
    session.commit()
    session.close()
    # NoApplicableCode("Could commit to database: {}".format(e.message))
github smicallef / spiderfoot / modules / sfp_archiveorg.py View on Github external
if eventName == "URL_JAVA_APPLET" and not self.opts['javapages']:
            return None
        if eventName == "URL_FLASH" and not self.opts['flashpages']:
            return None
        if eventName == "URL_JAVASCRIPT" and not self.opts['javascriptpages']:
            return None
        if eventName == "URL_WEB_FRAMEWORK" and not self.opts['webframeworkpages']:
            return None

        if eventData in self.results:
            return None
        else:
            self.results[eventData] = True

        for daysback in self.opts['farback'].split(","):
            newDate = datetime.datetime.now() - datetime.timedelta(days=int(daysback))
            maxDate = newDate.strftime("%Y%m%d")

            url = "https://archive.org/wayback/available?url=" + eventData + \
                  "&timestamp=" + maxDate
            res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], 
                                   useragent=self.opts['_useragent'])

            if res['content'] == None:
                self.sf.error("Unable to fetch " + url, False)
                continue

            try:
                ret = json.loads(res['content'])
            except BaseException as e:
                ret = None
github openstack / keystone / keystone / common / sql / contract_repo / versions / 002_password_created_at_not_nullable.py View on Github external
password = sql.Table('password', meta, autoload=True)
    # Because it's difficult to get a timestamp server default working among
    # all of the supported databases and versions, I'm choosing to drop and
    # then recreate the column as I think this is a more cleaner option. This
    # will only impact operators that have already deployed the 105 migration;
    # resetting the password created_at for security compliance features, if
    # enabled.
    password.c.created_at.drop()
    # sqlite doesn't support server_default=sql.func.now(), so skipping.
    if migrate_engine.name == 'sqlite':
        created_at = sql.Column('created_at', sql.TIMESTAMP, nullable=True)
    else:
        # Changing type to timestamp as mysql 5.5 and older doesn't support
        # datetime defaults.
        created_at = sql.Column('created_at', sql.TIMESTAMP, nullable=False,
                                default=datetime.datetime.utcnow,
                                server_default=sql.func.now())
    password.create_column(created_at)
github SymbiFlow / symbiflow-arch-defs / xc / common / utils / prjxray_edge_library.py View on Github external
import datetime
import functools
from collections import namedtuple
from lib.rr_graph import tracks
from lib.rr_graph import graph2
from prjxray.site_type import SitePinDirection
from prjxray_constant_site_pins import yield_ties_to_wire
from lib.connection_database import get_track_model, get_wire_in_tile_from_pin_name
from lib.rr_graph.graph2 import NodeType
import re
import math
import numpy

from prjxray_db_cache import DatabaseCache

now = datetime.datetime.now


def get_node_type(conn, graph_node_pkey):
    """ Returns the node type of a given graph node"""

    c = conn.cursor()
    c.execute(
        """
        SELECT graph_node_type FROM graph_node WHERE pkey = ?""",
        (graph_node_pkey, )
    )

    return c.fetchone()[0]


def get_pins(conn, site_type, site_pin):
github bluesky / databroker / databroker / v1.py View on Github external
def _pretty_print_time(timestamp):
    # timestamp needs to be a float or fromtimestamp() will barf
    timestamp = float(timestamp)
    dt = datetime.fromtimestamp(timestamp).isoformat()
    ago = humanize.naturaltime(time.time() - timestamp)
    return '{ago} ({date})'.format(ago=ago, date=dt)
github texuf / pymonster / pymonster / __init__.py View on Github external
def consume_events():
    ''' to be run in another process, hopefully another pyhsical machine '''
    for event_consumer in g_event_consumers:
        event_instance = event_consumer[0]
        consumer = event_consumer[1]
        kwargs = event_consumer[2] if len(event_consumer) > 2 else None
        start_time = datetime.now()
        while( (datetime.now() - start_time) < timedelta(minutes=5) ):
            event_data = event_instance.get_next(consumer.collection_name)
            if event_data is not None:
                logger( 'Consuming [%s][%s #%d]' % (consumer.collection_name, event_instance.collection_name, event_data['_id']) )
                if kwargs is not None:
                    consumer.consume(event_instance, event_data, **kwargs)
                else:
                    consumer.consume(event_instance, event_data)
            else:
                break
        #some logging to know if we're not processing things
        if event_data is not None:
            logger('failed to exhaust consumer [%s]' % consumer.collection_name)
github fengjinqi / website / apps / user / models.py View on Github external
return self.code

    class Meta:
        verbose_name='邮箱验证码'
        verbose_name_plural=verbose_name


class UserMessage(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user',verbose_name='收消息用户')
    to_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='to_user',verbose_name='发消息用户',blank=True,null=True)
    message = models.TextField(verbose_name='消息内容')
    ids = models.UUIDField(blank=True,null=True,verbose_name='评论文章id',)
    url = models.CharField(max_length=200,verbose_name='地址',blank=True,null=True)
    is_supper = models.BooleanField(default=False,verbose_name='是系统消息')
    has_read = models.BooleanField(default=False, verbose_name='是否已读')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')

    def __str__(self):
        return self.message

    class Meta:
        verbose_name ='用户消息'
        verbose_name_plural=verbose_name
        ordering = ('-add_time',)
github suminb / finance / finance / utils.py View on Github external
def parse_date(date, format='%Y-%m-%d'):
    """Make a datetime object from a string.

    :type date: str or int
    :rtype: datetime.date
    """
    if isinstance(date, int):
        return datetime.now().date() + timedelta(days=date)
    else:
        return datetime.strptime(date, format)