Python datetime.isoformat() Examples

The following are code examples for showing how to use datetime.isoformat(). 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: cloudburst   Author: brightband   File: utils.py    Mozilla Public License 2.0 6 votes vote down vote up
def datetime_handler(dt):
    """
    Handle datetime conversion for non-standard datetime
    formats during the conversion of dicts <-> json through
    the json library
     
    Args:
        dt (datetime.datetime): Datetime object to be
                                converted
     
    Returns:
        dt (datetime.isoformat): Datetime converted to ISO
                                 format
     
    Raises:
        TypeError: If the provided datetime object is not
                   of a type that we know how to convert
    """
    if isinstance(dt, datetime.datetime):
        return dt.isoformat()
    raise TypeError("Unknown type") 
Example 2
Project: Cirq   Author: quantumlib   File: calibration.py    Apache License 2.0 6 votes vote down vote up
def timestamp_str(self,
                      tz: Optional[datetime.tzinfo] = None,
                      timespec: str = 'auto') -> str:
        """Return a string for the calibration timestamp.

        Args:
            tz: The timezone for the string. If None, the method uses the
                platform's local date and time.
            timespec: See datetime.isoformat for valid values.

        Returns:
            The string in ISO 8601 format YYYY-MM-DDTHH:MM:SS.ffffff.
        """
        dt = datetime.datetime.fromtimestamp(self.timestamp / 1000, tz)
        dt += datetime.timedelta(microseconds=self.timestamp % 1000000)
        return dt.isoformat(sep=' ', timespec=timespec) 
Example 3
Project: versionalchemy   Author: NerdWalletOSS   File: utils.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        return super(VAJSONEncoder, self).default(obj) 
Example 4
Project: idact   Author: garstka   File: utc_from_str.py    MIT License 5 votes vote down vote up
def utc_from_str(value: str) -> datetime.datetime:
    """Converts a string to an aware datetime object.

        :param value: UTC datetime from :meth:`datetime.isoformat`.

    """
    return dateutil.parser.isoparse(value).replace(
        tzinfo=dateutil.tz.tzutc()) 
Example 5
Project: savage   Author: NerdWalletOSS   File: utils.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return super(SavageJSONEncoder, self).default(obj) 
Example 6
Project: InfosecDatasetCreationTools   Author: jinksunk   File: w3cloggeninterface.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        '''
        Initialize the data element with the following possible keyword arguments:
        * datetime -- default datetime.isoformat(sep=' ')
        * cip -- <required>
        * cusername -- default '-'
        * sip -- <required>
        * sport -- default '80'
        * csmethod -- default 'GET'
        * csuristem -- default '-'
        * csuriquery -- default '-'
        * scstatus -- default 200
        * csua -- default '-'
        * eventID -- required
        '''
        self.mylog.debug("Creating new W3CLog entry object id: {} from dict ID: {}")
        self.field_values = dict()
        for arg in self.default_kwargs.keys():
            if arg in kwargs:
                self.field_values[arg] = kwargs[arg]
            else:
                if self.default_kwargs[arg]:
                    self.field_values[arg] = self.default_kwargs[arg]
                else:
                    raise TypeError("Missing required argument {}".format(arg))
        
        self.field_values['datetime'] = datetime.datetime.fromtimestamp(
            self.field_values['datetime']).isoformat(' ')

        super(EventW3CEVT, self).__init__(self.get_time(), 
                                          self.get_eventID(), self.get_raw_element()) 
Example 7
Project: pairstrade-fyp-2019   Author: wywongbd   File: ptstrategy.py    MIT License 5 votes vote down vote up
def log(txt, dt=None, data=None):
        dt = dt or data.datetime[0]
        dt = bt.num2date(dt)
        _logger.info('%s, %s' % (dt.isoformat(), txt)) 
Example 8
Project: bitcoin   Author: isaacdlp   File: BitcoinBenchmark.py    MIT License 5 votes vote down vote up
def log(self, txt, dt=None):
        dt = dt or self.BTC.datetime.datetime()
        print('%s %s' % (dt.isoformat(), txt)) 
Example 9
Project: bitcoin   Author: isaacdlp   File: BitcoinAlgo.py    MIT License 5 votes vote down vote up
def log(self, txt, dt=None):
        dt = dt or self.BTC.datetime.datetime()
        print('%s %s' % (dt.isoformat(), txt))