Python datetime.timestamp() Examples

The following are 15 code examples of datetime.timestamp(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime , or try the search function .
Example #1
Source File: utils.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def all2datetime(arg):
    """Return a datetime object from an int (timestamp) or an iso
    formatted string '%Y-%m-%d %H:%M:%S'.

    """
    if isinstance(arg, datetime.datetime):
        return arg
    if isinstance(arg, basestring):
        for fmt in ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f',
                    '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f']:
            try:
                return datetime.datetime.strptime(arg, fmt)
            except ValueError:
                pass
        raise ValueError('time data %r does not match standard formats' % arg)
    if isinstance(arg, (int_types, float)):
        return datetime.datetime.fromtimestamp(arg)
    raise TypeError("%s is of unknown type." % repr(arg)) 
Example #2
Source File: poloniex.py    From cryptotik with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_trade_history(self,
                          pair: str="all",
                          limit: int=500,
                          since: int=int(time.time() - 2.419e+6),
                          until=int(time.time())
                          ) -> list:
        """
        Returns your trade history for a given market, specified by the <pair> POST parameter.
        You may specify "all" as the <pair> to receive your trade history for all markets.
        You may optionally specify a range via <since> and/or <until> POST parameters, given in UNIX timestamp format;
        if you do not specify a range, it will be limited to one day. You may optionally limit the number of entries returned using the <limit> parameter,
        up to a maximum of 10,000. If the <limit> parameter is not specified, no more than 500 entries will be returned.
        """

        query = {"command": "returnTradeHistory",
                 "currencyPair": self.format_pair(pair)}

        if since > time.time():
            raise APIError("AYYY LMAO start time is in the future, take it easy.")

        if since is not None:
            query.update({"start": str(since),
                          "end": str(until)}
                         )
        return self.api(query) 
Example #3
Source File: poloniex.py    From cryptotik with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_market_trade_history(self, market, depth=100):

        upstream = super(PoloniexNormalized, self).get_market_trade_history(market, depth)
        downstream = []

        for data in upstream:

            downstream.append({
                'timestamp': self._string_to_datetime(data['date']),
                'is_sale': is_sale(data['type']),
                'rate': float(data['rate']),
                'amount': float(data['amount']),
                'trade_id': data['globalTradeID']
            })

        return downstream 
Example #4
Source File: date_time.py    From yaql with Apache License 2.0 6 votes vote down vote up
def datetime_from_timestamp(timestamp, offset=ZERO_TIMESPAN):
    """:yaql:datetime

    Returns datetime object built by timestamp.

    :signature: datetime(timestamp, offset => timespan(0))
    :arg timestamp: timespan object to represent datetime
    :argType timestamp: number
    :arg offset: datetime offset in microsecond resolution, needed for tzinfo,
        timespan(0) by default
    :argType offset: timespan type
    :returnType: datetime object

    .. code::

        yaql> let(datetime(1256953732)) -> [$.year, $.month, $.day]
        [2009, 10, 31]
    """
    zone = _get_tz(offset)
    return DATETIME_TYPE.fromtimestamp(timestamp, tz=zone) 
Example #5
Source File: date_time.py    From yaql with Apache License 2.0 6 votes vote down vote up
def register(context):
    functions = (
        build_datetime, build_timespan, datetime_from_timestamp,
        datetime_from_string, now, localtz, utctz, utc,
        days, hours, minutes, seconds, milliseconds, microseconds,
        datetime_plus_timespan, timespan_plus_datetime,
        datetime_minus_timespan, datetime_minus_datetime,
        timespan_plus_timespan, timespan_minus_timespan,
        datetime_gt_datetime, datetime_gte_datetime,
        datetime_lt_datetime, datetime_lte_datetime,
        timespan_gt_timespan, timespan_gte_timespan,
        timespan_lt_timespan, timespan_lte_timespan,
        negative_timespan, positive_timespan,
        timespan_by_num, num_by_timespan, div_timespans, div_timespan_by_num,
        year, month, day, hour, minute, second, microsecond, weekday,
        offset, timestamp, date, time, replace, format_, is_datetime,
        is_timespan
    )

    for func in functions:
        context.register_function(func) 
Example #6
Source File: dtclient.py    From odoo-dingtalk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_bpms_instance_list(self, process_code, start_time, end_time=None, size=10, cursor=0):
		"""
		企业可以根据审批流的唯一标识,分页获取该审批流对应的审批实例。只能取到权限范围内的相关部门的审批实例
		"""
		start_time = datetime.timestamp(start_time)
		start_time = int(round(start_time * 1000))
		if end_time:
			end_time = datetime.timestamp(end_time)
			end_time = int(round(end_time * 1000))
		args = locals()
		url = get_request_url('dingtalk.smartwork.bpms.processinstance.list', self.access_token)
		params = {}
		for key in ('process_code', 'start_time', 'end_time', 'size', 'cursor'):
			if args.get(key, no_value) is not None:
				params.update({key: args[key]})

		return _http_call(url,params) 
Example #7
Source File: utils.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def datetime2timestamp(dtm):
    """Returns the timestamp (as a float value) corresponding to the
datetime.datetime instance `dtm`"""
    # Python 2/3 compat: python 3 has datetime.timestamp()
    try:
        return dtm.timestamp()
    except AttributeError:
        try:
            return time.mktime(dtm.timetuple()) + dtm.microsecond / (1000000.)
        except ValueError:
            # year out of range might happen
            return (dtm - datetime.datetime.fromtimestamp(0)).total_seconds() 
Example #8
Source File: utils.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def tz_offset(timestamp=None):
    """
    Returns the offset between UTC and local time at "timestamp".
    """
    if timestamp is None:
        timestamp = time.time()
    utc_offset = (datetime.datetime.fromtimestamp(timestamp) -
                  datetime.datetime.utcfromtimestamp(timestamp))
    return int(utc_offset.total_seconds()) 
Example #9
Source File: utils.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def datetime2utcdatetime(dtm):
    """
    Returns the given datetime in UTC. dtm is expected to be in local
    timezone.
    """
    offset = tz_offset(timestamp=datetime2timestamp(dtm))
    delta = datetime.timedelta(seconds=offset)
    return dtm - delta 
Example #10
Source File: poloniex.py    From cryptotik with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _to_timestamp(datetime):
        '''convert datetime to unix timestamp in python2 compatible manner.'''

        try:
            return datetime.timestamp()
        except AttributeError:
            return int(datetime.strftime('%s')) 
Example #11
Source File: poloniex.py    From cryptotik with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_chart_data(self,
                       pair: str,
                       period: int,
                       start: int=0,
                       until: int=int(time.time())
                       ) -> list:
        """
        Returns candlestick chart data.
        Required GET parameters are "currencyPair", "period" (candlestick period in seconds;
        valid values are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end".
        "Start" and "end" are given in UNIX timestamp format and used to specify the date range
        for the data returned. Sample output:
            [
                {
                    "date": 1405699200,
                    "high": 0.0045388,
                    "low": 0.00403001,
                    "open": 0.00404545,
                    "close": 0.00427592,
                    "volume": 44.11655644,
                    "quoteVolume": 10259.29079097,
                    "weightedAverage": 0.00430015
                },
                ...
                ]
        """

        query = {"command": "returnChartData",
                 "currencyPair": self.format_pair(pair),
                 "period": str(period),
                 "start": str(start),
                 "until": str(until)
                 }

        return self.api(query) 
Example #12
Source File: poloniex.py    From cryptotik with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _tstamp_to_datetime(timestamp):
        '''convert unix timestamp to datetime'''

        return datetime.datetime.fromtimestamp(timestamp) 
Example #13
Source File: date_time.py    From yaql with Apache License 2.0 5 votes vote down vote up
def timestamp(dt):
    """:yaql:property timestamp

    Returns total seconds from datetime(1970, 1, 1) to
    datetime UTC.

    :signature: datetime.timestamp
    :returnType: float

    .. code::

        yaql> datetime(2006, 11, 21, 16, 30).timestamp
        1164126600.0
    """
    return (utc(dt) - DATETIME_TYPE(1970, 1, 1, tzinfo=UTCTZ)).total_seconds() 
Example #14
Source File: dtclient.py    From odoo-dingtalk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def sign(self, ticket, nonce_str, time_stamp, url):
		import hashlib
		plain = 'jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}'.format(ticket, nonce_str, time_stamp, url)
		return  hashlib.sha1(plain).hexdigest() 
Example #15
Source File: dtclient.py    From odoo-dingtalk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_request_url(self, method, format_='json', v='2.0', simplify='false', partner_id=None):
		"""
		根据code获取请求地址
		"""
		timestamp = self.get_timestamp()
		url = '{0}?method={1}&session={2}&timestamp={3}&format={4}&v={5}'.format(
			_config['URL_METHODS_URL'], method, self.access_token, timestamp, format_, v)
		if format_ == 'json':
			url = '{0}&simplify={1}'.format(url, simplify)
		if partner_id:
			url = '{0}&partner_id={1}'.format(url, partner_id)
		return url