Python datetime 模块,isoformat() 实例源码

我们从Python开源项目中,提取了以下7个代码示例,用于说明如何使用datetime.isoformat()

项目:pyrsss    作者:butala    | 项目源码 | 文件源码
def plot_grid2D(lons, lats, tec_grid2D, datetime, title_label = ''):

    LATS, LONS = np.meshgrid(lats, lons)

    m = Basemap(llcrnrlon=-180,
                llcrnrlat=-55,
                urcrnrlon=180,
                urcrnrlat=75,
                projection='merc',
                area_thresh=1000,
                resolution='i')

    m.drawstates()
    m.drawcountries()
    m.drawcoastlines()

    parallels = np.arange(-90,90,20)
    m.drawparallels(parallels,labels=[True,False,False,True])
    meridians = np.arange(0,360,40)
    m.drawmeridians(meridians,labels=[True,False,False,True])

    m.scatter(LONS, LATS, c=tec_grid2D, latlon = True, linewidths=0, s=5)
    m.colorbar()

    plt.title('%s\n%s' % (title_label, datetime.isoformat(' ')))
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_datetime(self):
        """
        Test that a model with a datetime and date field is handled correctly
        """
        financial_aid = FinancialAidFactory.create(justification=None)
        assert serialize_model_object(financial_aid) == {
            'country_of_income': financial_aid.country_of_income,
            'country_of_residence': financial_aid.country_of_residence,
            'created_on': format_as_iso8601(financial_aid.created_on),
            'date_documents_sent': financial_aid.date_documents_sent.isoformat(),
            'date_exchange_rate': format_as_iso8601(financial_aid.date_exchange_rate),
            'id': financial_aid.id,
            'income_usd': financial_aid.income_usd,
            'justification': None,
            'original_currency': financial_aid.original_currency,
            'original_income': financial_aid.original_income,
            'status': financial_aid.status,
            'tier_program': financial_aid.tier_program.id,
            'updated_on': format_as_iso8601(financial_aid.updated_on),
            'user': financial_aid.user.id,
        }
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def format_as_iso8601(time):
    """Helper function to format datetime with the Z at the end"""
    # Can't use datetime.isoformat() because format is slightly different from this
    iso_format = '%Y-%m-%dT%H:%M:%S'
    formatted_time = time.strftime(iso_format)
    if time.microsecond:
        miniseconds_format = '.%f'
        formatted_time += time.strftime(miniseconds_format)[:4]
    return formatted_time + "Z"
项目:Tethys    作者:JosePedroMatos    | 项目源码 | 文件源码
def getDataForJSON(self, dateIni, dateEnd, returnData=True, returnInfo=True):
        # get data
        data = self.getData(dateIni, dateEnd)
        idxs = np.where((np.nansum(data['data']+1, axis=0)!=0).ravel())[0]
        idxsList = idxs.tolist()

        # trim data
        if len(data)>0: 
            data['dates'] = [dt.isoformat() for dt in data['dates']]
            data['missing'] = data['missing'].tolist()

            if returnInfo:
                data['lon'] = data['lon'].tolist()
                data['lat'] = data['lat'].tolist()
                data['idxs'] = idxsList
            else:
                data.pop('lon', None)
                data.pop('lat', None)
                data.pop('idxs', None)

            if returnData:
                tmp = []
                for i0 in range(data['data'].shape[0]):
                    tmpValidData = data['data'][i0,:,:].ravel()[idxsList]
                    tmpValidData[np.isnan(tmpValidData)] = -999;
                    tmpPositiveIdxs = np.where(tmpValidData!=0)[0]
                    tmp.append({'idxs': idxs[tmpPositiveIdxs].tolist(), 'values': tmpValidData[tmpPositiveIdxs].tolist()})
                data['data'] = tmp
            else:
                data.pop('data', None)

            return data
        else:
            return {}
项目:InfosecDatasetCreationTools    作者:jinksunk    | 项目源码 | 文件源码
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())
项目:versionalchemy    作者:NerdWalletOSS    | 项目源码 | 文件源码
def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return super(VAJSONEncoder, self).default(obj)
项目:opx-build    作者:open-switch    | 项目源码 | 文件源码
def art8601_format(dt):
    """
    Format datetime object in ISO 8601 format suitable for Artifactory.

    Artifactory's ISO 8601 timestamp parser is strict. It only accepts
    3 sigificant digits of sub-second precision (milliseconds) instead
    of the 6 significant digits (microseconds) in datetime.isoformat()
    output.

    I've raised a support ticket asking JFrog to consider relaxing
    their parser.

    Code adapted from standard python library.
    """

    s = '%04d-%02d-%02dT%02d:%02d:%02d.%03d' % (
        dt.year,
        dt.month,
        dt.day,
        dt.hour,
        dt.minute,
        dt.second,
        dt.microsecond / 1000)

    utc_offset = dt.utcoffset()
    if utc_offset is not None:
        if utc_offset.days < 0:
            sign = '-'
            utc_offset = - utc_offset
        else:
            sign = '+'

        hh, mm = divmod(utc_offset.seconds, 3600)
        mm //= 60

        s += "%s%02d%02d" % (sign, hh, mm)
    else:
        s += "Z"

    return s