def format(self, value): if not isinstance(value, datetime): return value configlet = getUtility(IFormatterConfiglet) tz = timezone(configlet.timezone) if value.tzinfo is None: value = utc.localize(value) value = value.astimezone(tz) offset = value.tzinfo.utcoffset(value) if offset < timedelta(): ind = -1 else: ind = 1 offset = ind*(abs(offset).seconds/600)*10 value = FixedOffset(offset).normalize(value) fdate = unicode(value.strftime(str(getattr(configlet,'date_'+self.tp)))) ftime = unicode(value.strftime(str(getattr(configlet,'time_'+self.tp)))) formatted = value.strftime('%B %d, %Y %H:%M:%S %z') return u'<span class="zojax-formatter-fancydatetime" date="%s" time="%s" offset="%s" value="%s" format="%s">%s</span>' \ % (fdate, ftime, offset, value.strftime('%B %d, %Y %H:%M:%S %z'), self.tp, formatted)
def value_from_raw(self, raw): if raw.value is None: return raw.missing_value('Missing datetime') try: chunks = raw.value.split(' ') date_info = [int(bit) for bit in chunks[0].split('-')] time_info = [int(bit) for bit in chunks[1].split(':')] datetime_info = date_info + time_info result = datetime(*datetime_info) if len(chunks) > 2: try: tz = get_timezone(chunks[-1]) except LookupError: if len(chunks[-1]) > 5: chunks[-1] = chunks[-1][-5:] delta = int(chunks[-1][1:3]) * 60 + int(chunks[-1][3:]) if chunks[-1][0] == '-': delta *= -1 tz = FixedOffset(delta) return tz.localize(result) return result except Exception: return raw.bad_value('Bad date format')
def convert_to_datetime(input, tz, arg_name): """ Converts the given object to a timezone aware datetime object. If a timezone aware datetime object is passed, it is returned unmodified. If a native datetime object is passed, it is given the specified timezone. If the input is a string, it is parsed as a datetime with the given timezone. Date strings are accepted in three different forms: date only (Y-m-d), date with time (Y-m-d H:M:S) or with date+time with microseconds (Y-m-d H:M:S.micro). Additionally you can override the time zone by giving a specific offset in the format specified by ISO 8601: Z (UTC), +HH:MM or -HH:MM. :param str|datetime input: the datetime or string to convert to a timezone aware datetime :param datetime.tzinfo tz: timezone to interpret ``input`` in :param str arg_name: the name of the argument (used in an error message) :rtype: datetime """ if input is None: return elif isinstance(input, datetime): datetime_ = input elif isinstance(input, date): datetime_ = datetime.combine(input, time()) elif isinstance(input, six.string_types): m = _DATE_REGEX.match(input) if not m: raise ValueError('Invalid date string') values = m.groupdict() tzname = values.pop('timezone') if tzname == 'Z': tz = utc elif tzname: hours, minutes = (int(x) for x in tzname[1:].split(':')) sign = 1 if tzname[0] == '+' else -1 tz = FixedOffset(sign * (hours * 60 + minutes)) values = {k: int(v or 0) for k, v in values.items()} datetime_ = datetime(**values) else: raise TypeError('Unsupported type for %s: %s' % (arg_name, input.__class__.__name__)) if datetime_.tzinfo is not None: return datetime_ if tz is None: raise ValueError( 'The "tz" argument must be specified if %s has no timezone information' % arg_name) if isinstance(tz, six.string_types): tz = timezone(tz) try: return tz.localize(datetime_, is_dst=None) except AttributeError: raise TypeError( 'Only pytz timezones are supported (need the localize() and normalize() methods)')
def format(self, value): configlet = getUtility(IFormatterConfiglet) tz = timezone(configlet.timezone) if value.tzinfo is None: value = utc.localize(value) value = value.astimezone(tz) now = datetime.now(utc) delta = now - value.astimezone(utc) key = 'past' if delta < timedelta(): delta = - delta + timedelta(seconds=1) #due to python implementation key = 'future' offset = value.tzinfo.utcoffset(value) if offset < timedelta(): ind = -1 else: ind = 1 offset = ind*(abs(offset).seconds/600)*10 value = FixedOffset(offset).normalize(value) years, months, weeks, hours, minutes = ( delta.days/365, delta.days/30, delta.days/7, delta.seconds/3600, delta.seconds/60) formatted = None if years > 0: formatted = translate(self.messages[key]['year'], 'zojax.formatter', mapping={'value': years}) elif months > 0: formatted = translate(self.messages[key]['month'],'zojax.formatter', mapping={'value': months}) elif weeks > 0: formatted = translate(self.messages[key]['week'], 'zojax.formatter', mapping={'value': weeks}) elif delta.days > 0: formatted = translate(self.messages[key]['day'], 'zojax.formatter', mapping={'value': delta.days}) elif hours > 0: formatted = translate(self.messages[key]['hour'], 'zojax.formatter', mapping={'value': hours}) elif minutes > 0: formatted = translate( self.messages[key]['minute'], 'zojax.formatter', mapping={'value': minutes}) else: formatted = translate( self.messages[key]['second'], 'zojax.formatter', mapping={'value': delta.seconds}) return """<span class="zojax-formatter-humandatetime" value="%s">%s</span>""" \ % (value.strftime('%B %d, %Y %H:%M:%S %z'), formatted)
def unique_nulls_fixture(request): """ Fixture for each null type in pandas, each null type exactly once """ return request.param # Generate cartesian product of unique_nulls_fixture: unique_nulls_fixture2 = unique_nulls_fixture TIMEZONES = [ None, 'UTC', 'US/Eastern', 'Asia/Tokyo', 'dateutil/US/Pacific', 'dateutil/Asia/Singapore', tzutc(), tzlocal(), FixedOffset(300), FixedOffset(0), FixedOffset(-300), timezone.utc, timezone(timedelta(hours=1)), timezone(timedelta(hours=-1), name='foo') ] @td.parametrize_fixture_doc(str(TIMEZONES)) @pytest.fixture(params=TIMEZONES) def tz_naive_fixture(request): """ Fixture for trying timezones including default (None): {0} """ return request.param
def test_whole_second_time_output(cypher_eval): value = cypher_eval("RETURN time('12:34:56')") assert isinstance(value, Time) assert value == Time(12, 34, 56, tzinfo=FixedOffset(0))
def test_datetime_with_timezone_offset(cls): b, unpacked = pack_and_unpack(cls(1970, 1, 1, 0, 0, 0, tzinfo=FixedOffset(1)), version=(2, 0)) assert b == b"\xB3F\x00\x00\x3C" assert unpacked == Structure(ord(b"F"), 0, 0, 60)
def test_datetime_with_numeric_time_offset(self): self.assert_supports_temporal_types() with self.driver.session() as session: result = session.run("RETURN datetime('1976-06-13T12:34:56.789012345+01:30')") value = result.single().value() self.assertIsInstance(value, DateTime) self.assertEqual(value, DateTime(1976, 6, 13, 12, 34, 56.789012345, tzinfo=FixedOffset(90)))
def test_datetime_with_numeric_time_offset(self): self.assert_supports_temporal_types() with self.driver.session() as session: result = session.run("CYPHER runtime=interpreted WITH $x AS x " "RETURN x.year, x.month, x.day, " " x.hour, x.minute, x.second, x.nanosecond, x.offset", x=DateTime(1976, 6, 13, 12, 34, 56.789012345, tzinfo=FixedOffset(90))) year, month, day, hour, minute, second, nanosecond, offset = result.single() self.assertEqual(year, 1976) self.assertEqual(month, 6) self.assertEqual(day, 13) self.assertEqual(hour, 12) self.assertEqual(minute, 34) self.assertEqual(second, 56) self.assertEqual(nanosecond, 789012345) self.assertEqual(offset, "+01:30")
# Time zones # ---------------------------------------------------------------- TIMEZONES = [ None, "UTC", "US/Eastern", "Asia/Tokyo", "dateutil/US/Pacific", "dateutil/Asia/Singapore", "+01:15", "-02:15", "UTC+01:15", "UTC-02:15", tzutc(), tzlocal(), FixedOffset(300), FixedOffset(0), FixedOffset(-300), timezone.utc, timezone(timedelta(hours=1)), timezone(timedelta(hours=-1), name="foo"), ] TIMEZONE_IDS = [repr(i) for i in TIMEZONES] @td.parametrize_fixture_doc(str(TIMEZONE_IDS)) @pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS) def tz_naive_fixture(request): """ Fixture for trying timezones including default (None): {0} """
def test_time_with_numeric_time_offset_output(cypher_eval): value = cypher_eval("RETURN time('12:34:56.789012345+0130')") assert isinstance(value, Time) assert value == Time(12, 34, 56.789012345, tzinfo=FixedOffset(90))
def run_energy_update_archive( year: Optional[int] = None, months: Optional[List[int]] = None, days: Optional[int] = None, regions: Optional[List[str]] = None, fueltech: Optional[str] = None, network: NetworkSchema = NetworkNEM, run_clear: bool = True, ) -> None: date_range = get_date_range(network=network) years: List[int] = [] if not year: years = [i for i in range(YEAR_EARLIEST, DATE_CURRENT_YEAR + 1)] else: years = [year] if not months: months = list(range(1, 13)) if not regions: regions = [i.code for i in get_network_regions(network)] # @TODO remove this and give APVI regions if network == NetworkAPVI: regions = ["WEM"] fueltechs = [fueltech] if not fueltech: fueltechs = [i for i in load_fueltechs().keys()] for y in years: for month in months: date_min = datetime(year=y, month=month, day=1, hour=0, minute=0, second=0, tzinfo=FixedOffset(600)) date_max = date_min + get_human_interval("1M") if days: date_max = datetime( year=y, month=month, day=1 + days, hour=0, minute=0, second=0, tzinfo=FixedOffset(600), ) date_min = date_min - timedelta(minutes=10) date_max = date_max + timedelta(minutes=10) if date_max > date_range.end: date_max = date_range.end if date_min > date_max: # slack_message("Reached end of energy archive") logger.debug("Reached end of archive {} {}".format( date_min, date_max)) break for region in regions: for fueltech_id in fueltechs: run_energy_calc( date_min, date_max, region=region, fueltech_id=fueltech_id, network=network, run_clear=run_clear, )
def test_nanosecond_resolution_time_output(cypher_eval): value = cypher_eval("RETURN time('12:34:56.789012345')") assert isinstance(value, Time) assert value == Time(12, 34, 56.789012345, tzinfo=FixedOffset(0))
def test_iso_format_with_time_zone_case_2(): # python -m pytest tests/unit/time/test_time.py -s -v -k test_iso_format_with_time_zone_case_2 expected = Time.from_iso_format("07:54:02.129790999+01:00") assert expected.tzinfo == FixedOffset(60) assert expected.iso_format() == "07:54:02.129790999+01:00"
def test_from_iso_format_with_negative_long_tz(self): expected = Time(12, 34, 56.123456789, tzinfo=FixedOffset(-754)) actual = Time.from_iso_format("12:34:56.123456789-12:34:56.123456") self.assertEqual(expected, actual)
def test_from_iso_format_with_positive_tz(self): expected = Time(12, 34, 56.123456789, tzinfo=FixedOffset(754)) actual = Time.from_iso_format("12:34:56.123456789+12:34") self.assertEqual(expected, actual)
def timestamp(self): """tz-aware version of date & time & tz_offset""" ts = dt.datetime.combine(self.date, self.time) ts = FixedOffset(60 * self.tz_offset).localize(ts) return ts
@pytest.fixture(params=[None, np.nan, pd.NaT]) def unique_nulls_fixture(request): """ Fixture for each null type in pandas, each null type exactly once """ return request.param # Generate cartesian product of unique_nulls_fixture: unique_nulls_fixture2 = unique_nulls_fixture TIMEZONES = [None, 'UTC', 'US/Eastern', 'Asia/Tokyo', 'dateutil/US/Pacific', 'dateutil/Asia/Singapore', tzutc(), tzlocal(), FixedOffset(300), FixedOffset(0), FixedOffset(-300)] @td.parametrize_fixture_doc(str(TIMEZONES)) @pytest.fixture(params=TIMEZONES) def tz_naive_fixture(request): """ Fixture for trying timezones including default (None): {0} """ return request.param @td.parametrize_fixture_doc(str(TIMEZONES[1:])) @pytest.fixture(params=TIMEZONES[1:]) def tz_aware_fixture(request):