当前位置: 首页>>代码示例>>Python>>正文


Python obspy.UTCDateTime类代码示例

本文整理汇总了Python中obspy.UTCDateTime的典型用法代码示例。如果您正苦于以下问题:Python UTCDateTime类的具体用法?Python UTCDateTime怎么用?Python UTCDateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了UTCDateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_weekday

 def test_weekday(self):
     """
     Tests weekday method.
     """
     dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
     self.assertEqual(dt.weekday, 2)
     self.assertEqual(dt._getWeekday(), 2)
开发者ID:avuan,项目名称:obspy,代码行数:7,代码来源:test_utcdatetime.py

示例2: test_toordinal

 def test_toordinal(self):
     """
     Short test if toordinal() is working.
     Matplotlib's date2num() function depends on this which is used a lot in
     plotting.
     """
     dt = UTCDateTime("2012-03-04T11:05:09.123456Z")
     self.assertEqual(dt.toordinal(), 734566)
开发者ID:avuan,项目名称:obspy,代码行数:8,代码来源:test_utcdatetime.py

示例3: read_srcfrechet

  def read_srcfrechet(self, filename=None, update=False):
    """ Read in source derivative of misfit function
        Dchi/Dxs, Dchi/Dmt
    """
    with open(filename, 'r') as f:
      lines = [ x for x in f.readlines() if not(x.startswith('#')) ]

    lines = [x.split() for x in lines]

    t0  = float(lines[0][0]);  dchi_dt0  = float(lines[0][1])
    tau = float(lines[1][0]);  dchi_dtau = float(lines[1][1])
    x   = float(lines[2][0]);  dchi_dx   = float(lines[2][1])
    y   = float(lines[3][0]);  dchi_dy   = float(lines[3][1])
    z   = float(lines[4][0]);  dchi_dz   = float(lines[4][1])
    mxx = float(lines[5][0]);  dchi_dmxx = float(lines[5][1])
    myy = float(lines[6][0]);  dchi_dmyy = float(lines[6][1])
    mzz = float(lines[7][0]);  dchi_dmzz = float(lines[7][1])
    mxy = float(lines[8][0]);  dchi_dmxy = float(lines[8][1])
    mxz = float(lines[9][0]);  dchi_dmxz = float(lines[9][1])
    myz = float(lines[10][0]); dchi_dmyz = float(lines[10][1])

    dchi_dxs = np.array([dchi_dx, dchi_dy, dchi_dz])

    dchi_dmt = np.zeros((3,3))
    dchi_dmt[0,0] = dchi_dmxx
    dchi_dmt[1,1] = dchi_dmyy
    dchi_dmt[2,2] = dchi_dmzz
    dchi_dmt[0,1] = dchi_dmxy
    dchi_dmt[1,0] = dchi_dmxy
    dchi_dmt[0,2] = dchi_dmxz
    dchi_dmt[2,0] = dchi_dmxz
    dchi_dmt[1,2] = dchi_dmyz
    dchi_dmt[2,1] = dchi_dmyz

    # check if the same as event info
    data = self.data
    event = data['event']
    #...

    # record 
    src_frechet = {
        't0':dchi_dt0,
        'tau':dchi_dtau,
        'xs':dchi_dxs,
        'mt':dchi_dmt,
        'stat': {'code':0, 'msg':"created on "+UTCDateTime.now().isoformat()}
        }

    if 'src_frechet' not in data:
      data['src_frechet'] = src_frechet
    elif update:
      data['src_frechet'].update(src_frechet)
      data['src_frechet']['stat']['code'] = 1
      data['src_frechet']['stat']['msg'] = "updated on "+UTCDateTime.now().isoformat()
    else:
      raise Exception('src_frechet already set, not updated.')
开发者ID:taotaokai,项目名称:sem_utils,代码行数:56,代码来源:misfit_new.py

示例4: test_format_iris_webservice

    def test_format_iris_webservice(self):
        """
        Tests the format IRIS webservice function.

        See issue #1096.
        """
        # These are parse slightly differently (1 microsecond difference but
        # the IRIS webservice string should be identical as its only
        # accurate to three digits.
        d1 = UTCDateTime(2011, 1, 25, 15, 32, 12.26)
        d2 = UTCDateTime("2011-01-25T15:32:12.26")

        self.assertEqual(d1.format_iris_web_service(), d2.format_iris_web_service())
开发者ID:andreww,项目名称:obspy,代码行数:13,代码来源:test_utcdatetime.py

示例5: _colormap_plot_beamforming_time

def _colormap_plot_beamforming_time(cmaps):
    """
    Plot for illustrating colormaps: beamforming.

    :param cmaps: list of :class:`~matplotlib.colors.Colormap`
    :rtype: None
    """
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates

    from obspy import UTCDateTime
    from obspy.signal.array_analysis import array_processing

    # Execute array_processing
    stime = UTCDateTime("20080217110515")
    etime = UTCDateTime("20080217110545")
    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=-3.0, slm_x=3.0, sll_y=-3.0, slm_y=3.0, sl_s=0.03,
        # sliding window properties
        win_len=1.0, win_frac=0.05,
        # frequency properties
        frqlow=1.0, frqhigh=8.0, prewhiten=0,
        # restrict output
        semb_thres=-1e9, vel_thres=-1e9, timestamp='mlabday',
        stime=stime, etime=etime
    )
    st = _get_beamforming_example_stream()
    out = array_processing(st, **kwargs)
    # Plot
    labels = ['rel.power', 'abs.power', 'baz', 'slow']
    xlocator = mdates.AutoDateLocator()
    for cmap in cmaps:
        fig = plt.figure()
        for i, lab in enumerate(labels):
            ax = fig.add_subplot(4, 1, i + 1)
            ax.scatter(out[:, 0], out[:, i + 1], c=out[:, 1], alpha=0.6,
                       edgecolors='none', cmap=cmap)
            ax.set_ylabel(lab)
            ax.set_xlim(out[0, 0], out[-1, 0])
            ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
            ax.xaxis.set_major_locator(xlocator)
            ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))
        fig.suptitle('AGFA skyscraper blasting in Munich %s' % (
            stime.strftime('%Y-%m-%d'), ))
        fig.autofmt_xdate()
        fig.subplots_adjust(left=0.15, top=0.95, right=0.95, bottom=0.2,
                            hspace=0)
    plt.show()
开发者ID:YongYuPku,项目名称:obspy,代码行数:49,代码来源:cm.py

示例6: test_to_python_date_time_objects

 def test_to_python_date_time_objects(self):
     """
     Tests getDate, getTime, getTimestamp and getDateTime methods.
     """
     dt = UTCDateTime(1970, 1, 1, 12, 23, 34, 456789)
     # as function
     self.assertEqual(dt._get_date(), datetime.date(1970, 1, 1))
     self.assertEqual(dt._get_time(), datetime.time(12, 23, 34, 456789))
     self.assertEqual(dt._get_datetime(), datetime.datetime(1970, 1, 1, 12, 23, 34, 456789))
     self.assertAlmostEqual(dt._get_timestamp(), 44614.456789)
     # as property
     self.assertEqual(dt.date, datetime.date(1970, 1, 1))
     self.assertEqual(dt.time, datetime.time(12, 23, 34, 456789))
     self.assertEqual(dt.datetime, datetime.datetime(1970, 1, 1, 12, 23, 34, 456789))
     self.assertAlmostEqual(dt.timestamp, 44614.456789)
开发者ID:andreww,项目名称:obspy,代码行数:15,代码来源:test_utcdatetime.py

示例7: DateTime2String

def DateTime2String(dt, compact=False):
    """
    Generates a valid SEED time string from a UTCDateTime object.
    """
    if isinstance(dt, UTCDateTime):
        return dt.formatSEED(compact)
    elif isinstance(dt, basestring):
        dt = dt.strip()
    if not dt:
        return ""
    try:
        dt = UTCDateTime(dt)
        return dt.formatSEED(compact)
    except:
        raise Exception("Invalid datetime %s: %s" % (type(dt), str(dt)))
开发者ID:CSchwarz1234,项目名称:obspy,代码行数:15,代码来源:utils.py

示例8: datetime_2_string

def datetime_2_string(dt, compact=False):
    """
    Generates a valid SEED time string from a UTCDateTime object.
    """
    if isinstance(dt, UTCDateTime):
        return dt.format_seed(compact)
    elif isinstance(dt, (str, native_str)):
        dt = dt.strip()
    if not dt:
        return ""
    try:
        dt = UTCDateTime(dt)
        return dt.format_seed(compact)
    except Exception:
        raise Exception("Invalid datetime %s: %s" % (type(dt), str(dt)))
开发者ID:junlysky,项目名称:obspy,代码行数:15,代码来源:utils.py

示例9: _time

 def _time(self, blocktime, param, val, offset):
     """
     change a EVT time format to Obspy UTCDateTime format
     :param blocktime : time in sec after 1980/1/1
     :param param: parameter with milliseconds values (in val)
     :param val: list of value
     :param offset: Not used
     """
     frame_time = blocktime
     if param > 0:
         frame_milli = val[param-offset]
     else:
         frame_milli = 0
     frame_time += 315532800  # diff between 1970/1/1 and 1980/1/1
     time = UTCDateTime(frame_time) + frame_milli/1000.0
     time.precison = 3
     return time
开发者ID:vcoeur61,项目名称:evt,代码行数:17,代码来源:evt_base.py

示例10: create_simple_inventory

def create_simple_inventory(
    network,
    station,
    latitude=None,
    longitude=None,
    elevation=None,
    depth=None,
    start_date=None,
    end_date=None,
    location_code="S3",
    channel_code="MX",
):
    """
    Create simple inventory with only location information,
    for ZNE component, especially usefull for synthetic data
    """
    azi_dict = {"MXZ": 0.0, "MXN": 0.0, "MXE": 90.0}
    dip_dict = {"MXZ": 90.0, "MXN": 0.0, "MXE": 0.0}
    channel_list = []

    if start_date is None:
        start_date = UTCDateTime(0)

    # specfem default channel code is MX
    for _comp in ["Z", "E", "N"]:
        _chan_code = "%s%s" % (channel_code, _comp)
        chan = Channel(
            _chan_code,
            location_code,
            latitude=latitude,
            longitude=longitude,
            elevation=elevation,
            depth=depth,
            azimuth=azi_dict[_chan_code],
            dip=dip_dict[_chan_code],
            start_date=start_date,
            end_date=end_date,
        )
        channel_list.append(chan)

    site = Site("N/A")
    sta = Station(
        station,
        latitude=latitude,
        longitude=longitude,
        elevation=elevation,
        channels=channel_list,
        site=site,
        creation_date=start_date,
        total_number_of_channels=3,
        selected_number_of_channels=3,
    )

    nw = Network(network, stations=[sta], total_number_of_stations=1, selected_number_of_stations=1)

    inv = Inventory([nw], source="SPECFEM3D_GLOBE", sender="Princeton", created=UTCDateTime.now())

    return inv
开发者ID:wjlei1990,项目名称:pytomo3d,代码行数:58,代码来源:utils.py

示例11: _parse_long_time

def _parse_long_time(time_bytestring, decode=True):
    if decode:
        time_string = time_bytestring.decode()
    else:
        time_string = time_bytestring
    if not time_string.strip():
        return None
    time_string, milliseconds = time_string[:-3], int(time_string[-3:])
    return (UTCDateTime.strptime(time_string, '%Y%j%H%M%S') +
            1e-3 * milliseconds)
开发者ID:junlysky,项目名称:obspy,代码行数:10,代码来源:util.py

示例12: _parse_long_time

def _parse_long_time(time_bytestring, decode=True):
    """
    :returns: POSIX timestamp as integer nanoseconds
    """
    if decode:
        time_string = time_bytestring.decode()
    else:
        time_string = time_bytestring
    if not time_string.strip():
        return None
    time_string, milliseconds = time_string[:-3], int(time_string[-3:])
    t = UTCDateTime.strptime(time_string, '%Y%j%H%M%S')
    nanoseconds = t._ns
    nanoseconds += milliseconds * 1000000
    return nanoseconds
开发者ID:Brtle,项目名称:obspy,代码行数:15,代码来源:util.py

示例13: test_year_2038_problem

 def test_year_2038_problem(self):
     """
     See issue #805
     """
     dt = UTCDateTime(2004, 1, 10, 13, 37, 4)
     self.assertEqual(dt.__str__(), '2004-01-10T13:37:04.000000Z')
     dt = UTCDateTime(2038, 1, 19, 3, 14, 8)
     self.assertEqual(dt.__str__(), '2038-01-19T03:14:08.000000Z')
     dt = UTCDateTime(2106, 2, 7, 6, 28, 16)
     self.assertEqual(dt.__str__(), '2106-02-07T06:28:16.000000Z')
开发者ID:avuan,项目名称:obspy,代码行数:10,代码来源:test_utcdatetime.py

示例14: add_stationxml_to_asdf

def add_stationxml_to_asdf(ds, staxml_filelist, event=None,
                           create_simple_inv=False, sta_dict=None,
                           status_bar=False):
    # Add StationXML files.
    if create_simple_inv:
        if event is None:
            start_date = UTCDateTime.now()
        else:
            origin = event.preferred_origin() or event.origins[0]
            event_time = origin.time
            start_date = event_time - 300.0
        nstaxml = len(sta_dict)
        count = 0
        for tag, value in sta_dict.iteritems():
            count += 1
            inv = create_simple_inventory(
                value[0], value[1], latitude=value[2], longitude=value[3],
                elevation=value[4], depth=value[5], start_date=start_date)
            ds.add_stationxml(inv)
            if status_bar > 0:
                drawProgressBar((count)/nstaxml,
                                "Adding StationXML(created) data")
    else:
        nstaxml = len(staxml_filelist)
        if staxml_filelist is not None and nstaxml > 0:
            for _i, filename in enumerate(staxml_filelist):
                if not os.path.exists(filename):
                    raise ValueError("Staxml not exist %i of %i: %s"
                                     % (_i, nstaxml, filename))
                try:
                    ds.add_stationxml(filename)
                except Exception as err:
                    print("Error convert(%s) due to:%s" % (filename, err))
                if status_bar > 0:
                    drawProgressBar((_i+1)/nstaxml, "Adding StationXML data")
        else:
            print("No stationxml added")
开发者ID:wjlei1990,项目名称:pypaw,代码行数:37,代码来源:convert.py

示例15: _read_knet_hdr

def _read_knet_hdr(hdrlines, convert_stnm=False, **kwargs):
    """
    Read the header values into a dictionary.

    :param hdrlines: List of the header lines of a a K-NET/KiK-net ASCII file
    :type hdrlines: list
    :param convert_stnm: For station names with 6 letters write the last two
        letters of the station code to the 'location' field
    :type convert_stnm: bool
    """
    hdrdict = {'knet': {}}
    hdrnames = ['Origin Time', 'Lat.', 'Long.', 'Depth. (km)', 'Mag.',
                'Station Code', 'Station Lat.', 'Station Long.',
                'Station Height(m)', 'Record Time', 'Sampling Freq(Hz)',
                'Duration Time(s)', 'Dir.', 'Scale Factor', 'Max. Acc. (gal)',
                'Last Correction', 'Memo.']
    _i = 0
    # Event information
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    dt = flds[2] + ' ' + flds[3]
    dt = UTCDateTime.strptime(dt, '%Y/%m/%d %H:%M:%S')
    # All times are in Japanese standard time which is 9 hours ahead of UTC
    dt -= 9 * 3600.
    hdrdict['knet']['evot'] = dt

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    lat = float(flds[1])
    hdrdict['knet']['evla'] = lat

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    lon = float(flds[1])
    hdrdict['knet']['evlo'] = lon

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    dp = float(flds[2])
    hdrdict['knet']['evdp'] = dp

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    mag = float(flds[1])
    hdrdict['knet']['mag'] = mag

    # Station information
    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    # K-NET and KiK-Net station names can be more than 5 characters long
    # which will cause the station name to be truncated when writing the
    # the trace as miniSEED; if convert_stnm is enabled, the last two
    # letters of the station code are written to the 'location' field
    stnm = flds[2]
    location = ''
    if convert_stnm and len(stnm) > 5:
        location = stnm[-2:]
        stnm = stnm[:-2]
    if len(stnm) > 7:
        raise KNETException(
            "Station name can't be more than 7 characters long!")
    hdrdict['station'] = stnm
    hdrdict['location'] = location

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    hdrdict['knet']['stla'] = float(flds[2])

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    hdrdict['knet']['stlo'] = float(flds[2])

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    hdrdict['knet']['stel'] = float(flds[2])

    # Data information
    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    dt = flds[2] + ' ' + flds[3]
    # A 15 s delay is added to the record time by the
    # the K-NET and KiK-Net data logger
    dt = UTCDateTime.strptime(dt, '%Y/%m/%d %H:%M:%S') - 15.0
    # All times are in Japanese standard time which is 9 hours ahead of UTC
    dt -= 9 * 3600.
    hdrdict['starttime'] = dt

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    freqstr = flds[2]
    m = re.search('[0-9]*', freqstr)
    freq = int(m.group())
    hdrdict['sampling_rate'] = freq

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    hdrdict['knet']['duration'] = float(flds[2])

    _i += 1
    flds = _prep_hdr_line(hdrnames[_i], hdrlines[_i])
    channel = flds[1].replace('-', '')
#.........这里部分代码省略.........
开发者ID:Brtle,项目名称:obspy,代码行数:101,代码来源:knet.py


注:本文中的obspy.UTCDateTime类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。