def get_day_trade_minute_line(product, date): """ 返回一天内指定合约交易时段内所有分钟计算点 最后一分钟没有交易 :param symbol: :param date: DateTime :return: """ entries = get_trade_timetable_template(product) result = [] for w in range(len(entries)): s, e = entries[w][:2] dts = DateTime(date.year, date.month, date.day, s.hour, s.minute, s.second) dte = DateTime(date.year, date.month, date.day, e.hour, e.minute, e.second) # - TimeDelta(minutes=1) if len(entries[w]) == 3 and entries[w][-1].count('-'): # 跨天 dts += TimeDelta(days=1) dte += TimeDelta(days=1) else: if dte < dts: # 跨天的行情 dte = dte + TimeDelta(days=1) dte -= TimeDelta(minutes=1) # 不包括收尾分钟 mins = list(rrule(MINUTELY, interval=1, dtstart=dts, until=dte)) result += mins return result
def __init__(self, device_type='grid', device_id=None, sim_model=ParNotSet, control_model=ParNotSet, price_profile=None, profile_t0=DateTime(2018, 12, 3), forecast_lag='1D', param_struct=None): sim_model = sim_model if sim_model is not ParNotSet else GridModel( param_struct=param_struct, num_devices=0) control_model = control_model if control_model is not ParNotSet else sim_model super().__init__(device_type=device_type, device_id=device_id, sim_model=sim_model, control_model=control_model, profile_t0=DateTime(2018, 12, 3), forecast_lag=forecast_lag) self.price_profile = None self.set_price_profile(price_profile=price_profile, profile_t0=profile_t0) self._devices_struct: MutableMapping[AnyStr, MutableMapping[ int, MicroGridDeviceAgent]] = GridDevicesStruct() self._devices: Tuple_T[MicroGridDeviceAgent] = ()
def dateTimes(beforeNow: bool = False, fromNow: bool = False) -> SearchStrategy: # DateTime assert not (beforeNow and fromNow) # # min_value >= UTC epoch because otherwise we can't store dates as UTC # timestamps. # # We actually add a day of fuzz below because min_value doesn't allow # non-naive values (?!) so that ensures we have a value after the epoch # # For all current uses of model date-times in model objects in this module, # limiting values to those past the is totally OK. # fuzz = TimeDelta(days=1) if beforeNow: max = DateTime.now() - fuzz else: max = DateTime(9999, 12, 31, 23, 59, 59, 999999) if fromNow: min = DateTime.now() + fuzz else: min = DateTime(1970, 1, 1) + fuzz return _datetimes(min_value=min, max_value=max, timezones=timeZones())
def get_year_movies(year: int) -> OrderedDict: start_date: DateTime = DateTime(year, 1, 1, 0, 0, 0) end_date: DateTime = DateTime(year + 1, 1, 1, 0, 0, 0) docs = db.collection(MOVIES).where('date', '>=', start_date).where( 'date', '<', end_date).stream() result = OrderedDict() for doc in docs: result[doc.id] = doc.to_dict() return result
def test_init(): text = 'オカダ・カズチカ 内藤 哲也' begin_date = Date(2020, 10, 13) end_date = Date(2020, 10, 13) actual = SearchCondition(text=text, begin_date=begin_date, end_date=end_date) assert actual.keywords == ["オカダ", "カズチカ", "内藤", "哲也"] assert actual.begin_date == DateTime(2020, 10, 13) assert actual.end_date == DateTime(2020, 10, 13, 23, 59, 59)
def test_init_sortedEntries(self): """ L{Incident.reportEntries} is sorted. """ r1 = ReportEntry(u"", u"", created=DateTime(1972, 6, 29, 12, 0, 1)) r2 = ReportEntry(u"", u"", created=DateTime(1972, 6, 29, 12, 0, 2)) for entries in ((r1, r2), (r2, r1)): incident = newIncident(reportEntries=entries) self.assertEquals((r1, r2), incident.reportEntries)
def test_default_sensor_constructor(self): """ method: test get_type_name """ settings = ['closed', 'open'] sut = logger.DefaultSensor('RANGE', 1, '06:00:00', '16:00:00', 'Door', settings) self.assertEqual('range', sut.valid_type) self.assertEqual(1, sut.valid_value) self.assertEqual(DateTime(1900, 1, 1, 6, 0), sut.start_time) self.assertEqual(DateTime(1900, 1, 1, 16, 0), sut.end_time) self.assertEqual('Door', sut.name) self.assertEqual(settings, sut.settings)
def test_ordering(self): """ L{ReportEntry} implements ordering correctly. """ # Define r2 first so we might notice if sort order is (incorrectly) # defined by object id (which seems to be the default in CPython) r2 = ReportEntry(u"", u"", created=DateTime(1972, 6, 29, 12, 0, 2)) r1 = ReportEntry(u"", u"", created=DateTime(1972, 6, 29, 12, 0, 1)) r3 = ReportEntry(u"", u"", created=DateTime(1972, 6, 29, 12, 0, 3)) for entries in ((r1, r2, r3), (r3, r2, r1)): self.assertEquals(sorted(entries), [r1, r2, r3])
def __init__(self): self.disp = Display(Pin(DC), Pin(RES), Pin(CS), W, H, B) self.disp.show_progress('Start', 3) self.th = TempHumi(Pin(DHT)) self.sgp = CO2TVOC(Pin(SCL), Pin(SDA)) self.wireless = Wireless(WIFI_NAME, WIFI_PASSWORD) self.datetime = DateTime(self.wireless) self.logger = Logger(LOG_FILENAME) self.logger.write_startlog('\nSTART\n') self.pubcli = MQTT_CLI(self.wireless, MQTT_CLIENT_NAME, MQTT_SEVER_IP) self._count = 0 self._boarder_state = True
def test_eq_different(self): """ L{ReportEntry.__eq__} between two different entries. """ entry1 = ReportEntry( author=u"Tool", text=u"Something happened!", created=DateTime(1972, 6, 29, 12, 0, 0), ) entry2 = ReportEntry( author=u"Tool", text=u"Something else happened!", created=DateTime(1972, 6, 29, 12, 0, 0), ) self.assertNotEquals(entry1, entry2)
def test_can_store_datetime_with_timezone(self): dt = DateTime(2013, 5, 25, 9, 53, 24, tzinfo=FixedOffsetTimezone(-90)) inserted_id = self._insert_data(self.table, [{'timestamp': dt}]) dt_from_db = self._fetch_value(self.table, id=inserted_id) assert_equals(dt, dt_from_db) assert_equals(UTC, dt_from_db.tzinfo)
def test_can_parse_borg_json_with_single_archive(self): json_bytes = ( b'{\n' b'"archives": [\n' b' {\n' b' "archive": "2016-03-31T12:34:56+0200",\n' b' "barchive": "2016-03-31T12:34:56+0200",\n' b' "id": "078e9bccb4f54ad9836d78bc414aba883815821075e847b898ff7769cfd9849d",\n' b' "name": "2016-03-31T12:34:56+0200",\n' b' "start": "2016-03-31T12:34:57.000000",\n' b' "time": "2016-03-31T12:34:57.000000"\n' b' }\n' b' ],\n' b'"encryption": {\n' b' "keyfile": "/home/foo/.config/borg/keys/run_user_1000_storage",\n' b' "mode": "keyfile"\n' b'},\n' b'"repository": {\n' b' "id": "4dd2376c6e4f45689c583dc929a36351df3a986b0a6b44448912e4080b7c66a9",\n' b' "last_modified": "2017-10-24T17:19:13.000000",\n' b' "location": "ssh://[email protected]/borg/client"\n' b'}\n' b'}\n') archives = parse_borg_archive_listing(json_bytes) assert_length(1, archives) archive = archives[0] assert_equals('2016-03-31T12:34:56+0200', archive.name) assert_equals(DateTime(2016, 3, 31, 12, 34, 57), archive.time)
def test_format_datetime_rfc2822(self, d): offset_str, offset = d offset_td = TimeDelta(minutes=offset) tz = ConstantTZInfo(offset=offset_td) dt = DateTime(2020, 7, 21, hour=23, minute=2, second=59, tzinfo=tz) expected_str = 'Tue, 21 Jul 2020 23:02:59 ' + offset_str assert_equals(expected_str, format_datetime_rfc2822(dt))
def __init__(self, device_type=None, device_id=None, sim_model=ParNotSet, control_model=ParNotSet, omega_profile=None, profile_t0=DateTime(2018, 12, 3), omega_scenarios_profile=None, scenarios_t0=pd.Timedelta(0), forecast_lag='1D'): super().__init__(device_type=device_type, device_id=device_id, sim_model=sim_model, control_model=control_model) self.omega_profile = None self.profile_t0 = profile_t0 self.set_omega_profile(omega_profile=omega_profile, profile_t0=profile_t0) self.omega_scenarios = None self._omega_scenario_values = None self.intervals_per_day = None self.num_scenarios = None self.scenarios_t0 = scenarios_t0 self.set_omega_scenarios( omega_scenarios_profile=omega_scenarios_profile, scenarios_t0=scenarios_t0) self.forecast_lag = forecast_lag self._variables_k_act = None
def parse_pubmedpubdate_node(node): """ Parse the pubmedpubdate node of the xml response from pubmed api Parameters ---------- node : XML node or None Returns ------- status : str or None date: date or None """ if node is None: return None, None status = node.get("PubStatus") # Define default values for the date time object result = {"year": None, "month": 1, "day": 1, "hour": 0, "minute": 0} # Replace default values if possible for x in ("Year", "Month", "Day", "Hour", "Minute"): try: result[x.lower()] = int(node.find(x).text) except (TypeError, AttributeError, ValueError): continue if result["year"] is None: return status, None else: return status, DateTime(**result)
def test_datetimeAsRFC3339Naive(self): """ L{datetimeAsRFC3339} returns a proper RFC 3339 string for the given naive L{DateTime}, which is assumed to be UTC. """ self.assertRaises(ValueError, datetimeAsRFC3339, DateTime(1971, 4, 20, 16, 20, 4, tzinfo=None))
def test_eq_equal(self): """ L{ReportEntry.__eq__} between equal entries. """ entry1a = ReportEntry( author=u"Tool", text=u"Something happened!", created=DateTime(1972, 6, 29, 12, 0, 0), ) entry1b = ReportEntry( author=u"Tool", text=u"Something happened!", created=DateTime(1972, 6, 29, 12, 0, 0), ) self.assertEquals(entry1a, entry1a) self.assertEquals(entry1a, entry1b)
def _extract_match_date(title: str) -> Optional[DateTime]: match = re.search(r'\d{4}年\d{1,2}月\d{1,2}日', title) if match is not None: date_str = match.group() el = re.sub(r'(年|月|日)', '-', date_str).split('-') return DateTime(int(el[0]), int(el[1]), int(el[2])) match = re.search(r'\w{3,5}\s\d{1,2},\s*\d{4}', title) if match is not None: print(match) date_str = match.group() el = re.sub(r'(\s|,\s*)', '-', date_str).split('-') print(el) return DateTime(int(el[2]), _convert_month(el[0]), int(el[1])) return None
def test_rfc3339AsDatetime(self): """ L{rfc3339AsDateTime} returns a proper UTC L{DateTime} for the given RFC 3339 string. """ self.assertEquals(rfc3339AsDateTime("1971-04-20T16:20:04Z"), DateTime(1971, 4, 20, 16, 20, 4, tzinfo=utc))
def __init__(self, device_type='resd', device_id=None, sim_model=ParNotSet, control_model=ParNotSet, omega_profile=None, profile_t0=DateTime(2018, 12, 3), omega_scenarios_profile=None, scenarios_t0=pd.Timedelta(0), forecast_lag='1D', param_struct=None): sim_model = sim_model if sim_model is not ParNotSet else ResDemandModel( param_struct=param_struct) control_model = control_model if control_model is not ParNotSet else sim_model super().__init__(device_type=device_type, device_id=device_id, sim_model=sim_model, control_model=control_model, omega_profile=omega_profile, profile_t0=profile_t0, omega_scenarios_profile=omega_scenarios_profile, scenarios_t0=scenarios_t0, forecast_lag=forecast_lag)
def test_parsing_timezone(self): class Test(xsd.ComplexType): datetime = xsd.Element(xsd.DateTime) XML = '''<root><datetime>2011-06-30T20:19:00+01:00</datetime></root>''' test = Test.parsexml(XML) assert_equals(DateTime(2011, 6, 30, 19, 19, 0), test.datetime.astimezone(UTC).replace(tzinfo=None))
def test_datetimeAsRFC3339UTC(self): """ L{datetimeAsRFC3339} returns a proper RFC 3339 string for the given UTC L{DateTime}. """ self.assertEquals( datetimeAsRFC3339(DateTime(1971, 4, 20, 16, 20, 4, tzinfo=utc)), "1971-04-20T16:20:04Z")
def _get_date(article) -> DateTime: for span in article.select('span'): if 'data-dateformat' in span.attrs: date_str_list = span.text.split(' ') month = _get_month(date_str_list[0]) day = int(date_str_list[1].replace(',', '')) year = int(date_str_list[2]) return DateTime(year, month, day) raise ValueError
def test_can_correctly_determine_utc_offset(self): # Ensure that the DateTime type really uses the correct UTC offset # depending on the passed datetime value. class SummerWinterTZ(tzinfo): def utcoffset(self, dt): if dt.month in (10, 11, 12, 1, 2, 3): return TimeDelta(0) return TimeDelta(hours=1) def dst(self, dt): return TimeDelta(hours=1) tz = SummerWinterTZ() xsd_dt = xsd.DateTime() assert_equals('2013-11-26T00:00:00+00:00', xsd_dt.xmlvalue(DateTime(2013, 11, 26, tzinfo=tz))) assert_equals('2013-07-26T00:00:00+01:00', xsd_dt.xmlvalue(DateTime(2013, 7, 26, tzinfo=tz)))
def test_accepts_only_compatible_types(self): self.assert_can_set(None) self.assert_can_set(XSDDate(2012, 10, 26)) self.assert_can_set(Date(2013, 10, 26)) self.assert_can_not_set(0) self.assert_can_not_set([]) self.assert_can_not_set('invalid') self.assert_can_not_set(DateTime(2013, 10, 26))
def test_eq_other(self): """ L{ReportEntry.__eq__} between entry and other type. """ entry = ReportEntry( author=u"Tool", text=u"Something happened!", created=DateTime(1972, 6, 29, 12, 0, 0), ) self.assertNotEquals(entry, object())
def test_datetimeAsRFC3339Other(self): """ L{datetimeAsRFC3339} returns a proper RFC 3339 string for the given non-UTC L{DateTime}. """ tz = FixedOffsetTimeZone.fromSignHoursMinutes("+", 4, 20) self.assertEquals( datetimeAsRFC3339(DateTime(1971, 4, 20, 20, 40, 4, tzinfo=tz)), "1971-04-20T16:20:04Z")
def _get_day_trade_nminute_line(product, nmin, date): """ 返回一天内指定合约交易时段内指定n分钟间隔的时间计算点 最后一分钟没有交易 nmin - 3m 5m 15m 30m 60m """ result = [] if nmin not in (3, 5, 15, 30, 60): return result entries = get_trade_timetable_template(product) for w in range(len(entries)): s, e = entries[w][:2] smin = emin = 0 if s.minute: smin = s.minute / nmin * nmin if e.minute: emin = e.minute / nmin * nmin dts = DateTime(date.year, date.month, date.day, s.hour, s.minute, s.second) dte = DateTime(date.year, date.month, date.day, e.hour, e.minute, e.second) #- TimeDelta(minutes=1) if len(entries[w]) == 3 and entries[w][-1].count('-'): # 跨天 dts += TimeDelta(days=1) dte += TimeDelta(days=1) else: if dte < dts: # 跨天的行情 dte = dte + TimeDelta(days=1) dts = dts.replace(minute=smin, second=0, microsecond=0) dte = dte.replace(minute=emin, second=0, microsecond=0) if nmin != 60: dte -= TimeDelta(minutes=1) mins = list(rrule(MINUTELY, interval=nmin, dtstart=dts, until=dte)) # 间隔为3 for min in mins: if result.count(min) == 0: result.append(min) # result+=mins return result
def test_can_parse_queue_metadata(self): queue_date = DateTime(2020, 10, 1, hour=15, minute=42, second=21, tzinfo=LocalTZ) last_attempt = DateTime(2020, 10, 1, hour=16, minute=0, tzinfo=LocalTZ) retry_attempts = 3 queue_fp = build_queued_message( sender='*****@*****.**', recipient = '*****@*****.**', queue_date = queue_date, last = last_attempt, retries = retry_attempts, msg=b'RFC-821 MESSAGE', ) msg_info = parse_message_envelope(queue_fp) assert_equals('*****@*****.**', msg_info.from_addr) assert_equals(('*****@*****.**',), msg_info.to_addrs) assert_equals(queue_date, msg_info.queue_date) assert_equals(last_attempt, msg_info.last) assert_equals(retry_attempts, msg_info.retries) assert_equals(b'RFC-821 MESSAGE', msg_info.msg_fp.read())
def test_asTimeStamp_preEpoch(self) -> None: """ :func:`asTimeStamp` raises :exc:`StorageError` when given a time stamp before the UTC Epoch. """ epoch = DateTime( year=1970, month=1, day=1, hour=0, minute=0, tzinfo=TimeZone.utc ) preEpoch = epoch - TimeDelta(seconds=1) e = self.assertRaises(StorageError, asTimeStamp, preEpoch) self.assertStartsWith(str(e), "DateTime is before the UTC epoch: ")