Python datetime.time.tzinfo() Examples
The following are 30
code examples of datetime.time.tzinfo().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
datetime.time
, or try the search function
.
Example #1
Source File: datetimes.py From vnpy_crypto with MIT License | 6 votes |
def _assert_tzawareness_compat(self, other): # adapted from _Timestamp._assert_tzawareness_compat other_tz = getattr(other, 'tzinfo', None) if is_datetime64tz_dtype(other): # Get tzinfo from Series dtype other_tz = other.dtype.tz if other is libts.NaT: # pd.NaT quacks both aware and naive pass elif self.tz is None: if other_tz is not None: raise TypeError('Cannot compare tz-naive and tz-aware ' 'datetime-like objects.') elif other_tz is None: raise TypeError('Cannot compare tz-naive and tz-aware ' 'datetime-like objects')
Example #2
Source File: dates.py From pySINDy with MIT License | 6 votes |
def get_timezone(zone=None): """Looks up a timezone by name and returns it. The timezone object returned comes from ``pytz`` and corresponds to the `tzinfo` interface and can be used with all of the functions of Babel that operate with dates. If a timezone is not known a :exc:`LookupError` is raised. If `zone` is ``None`` a local zone object is returned. :param zone: the name of the timezone to look up. If a timezone object itself is passed in, mit's returned unchanged. """ if zone is None: return LOCALTZ if not isinstance(zone, string_types): return zone try: return _pytz.timezone(zone) except _pytz.UnknownTimeZoneError: raise LookupError('Unknown timezone %s' % zone)
Example #3
Source File: dates.py From pySINDy with MIT License | 6 votes |
def _format_fallback_interval(start, end, skeleton, tzinfo, locale): if skeleton in locale.datetime_skeletons: # Use the given skeleton format = lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale) elif all((isinstance(d, date) and not isinstance(d, datetime)) for d in (start, end)): # Both are just dates format = lambda dt: format_date(dt, locale=locale) elif all((isinstance(d, time) and not isinstance(d, date)) for d in (start, end)): # Both are times format = lambda dt: format_time(dt, tzinfo=tzinfo, locale=locale) else: format = lambda dt: format_datetime(dt, tzinfo=tzinfo, locale=locale) formatted_start = format(start) formatted_end = format(end) if formatted_start == formatted_end: return format(start) return ( locale.interval_formats.get(None, "{0}-{1}"). replace("{0}", formatted_start). replace("{1}", formatted_end) )
Example #4
Source File: dates.py From sndlatr with Apache License 2.0 | 6 votes |
def get_timezone(zone=None): """Looks up a timezone by name and returns it. The timezone object returned comes from ``pytz`` and corresponds to the `tzinfo` interface and can be used with all of the functions of Babel that operate with dates. If a timezone is not known a :exc:`LookupError` is raised. If `zone` is ``None`` a local zone object is returned. :param zone: the name of the timezone to look up. If a timezone object itself is passed in, mit's returned unchanged. """ if zone is None: return LOCALTZ if not isinstance(zone, string_types): return zone try: return _pytz.timezone(zone) except _pytz.UnknownTimeZoneError: raise LookupError('Unknown timezone %s' % zone)
Example #5
Source File: datetimes.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def indexer_at_time(self, time, asof=False): """ Returns index locations of index values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or string datetime.time or string in appropriate format ("%H:%M", "%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p", "%I%M%S%p"). Returns ------- values_at_time : array of integers See Also -------- indexer_between_time, DataFrame.at_time """ from dateutil.parser import parse if asof: raise NotImplementedError("'asof' argument is not supported") if isinstance(time, compat.string_types): time = parse(time).time() if time.tzinfo: # TODO raise NotImplementedError("argument 'time' with timezone info is " "not supported") time_micros = self._get_time_micros() micros = _time_to_micros(time) return (micros == time_micros).nonzero()[0]
Example #6
Source File: datetimes.py From recruit with Apache License 2.0 | 5 votes |
def get_value_maybe_box(self, series, key): # needed to localize naive datetimes if self.tz is not None: key = Timestamp(key) if key.tzinfo is not None: key = key.tz_convert(self.tz) else: key = key.tz_localize(self.tz) elif not isinstance(key, Timestamp): key = Timestamp(key) values = self._engine.get_value(com.values_from_object(series), key, tz=self.tz) return com.maybe_box(self, values, series, key)
Example #7
Source File: dates.py From pySINDy with MIT License | 5 votes |
def _get_dt_and_tzinfo(dt_or_tzinfo): """ Parse a `dt_or_tzinfo` value into a datetime and a tzinfo. See the docs for this function's callers for semantics. :rtype: tuple[datetime, tzinfo] """ if dt_or_tzinfo is None: dt = datetime.now() tzinfo = LOCALTZ elif isinstance(dt_or_tzinfo, string_types): dt = None tzinfo = get_timezone(dt_or_tzinfo) elif isinstance(dt_or_tzinfo, integer_types): dt = None tzinfo = UTC elif isinstance(dt_or_tzinfo, (datetime, time)): dt = _get_datetime(dt_or_tzinfo) if dt.tzinfo is not None: tzinfo = dt.tzinfo else: tzinfo = UTC else: dt = None tzinfo = dt_or_tzinfo return dt, tzinfo
Example #8
Source File: dates.py From pySINDy with MIT License | 5 votes |
def _ensure_datetime_tzinfo(datetime, tzinfo=None): """ Ensure the datetime passed has an attached tzinfo. If the datetime is tz-naive to begin with, UTC is attached. If a tzinfo is passed in, the datetime is normalized to that timezone. >>> _ensure_datetime_tzinfo(datetime(2015, 1, 1)).tzinfo.zone 'UTC' >>> tz = get_timezone("Europe/Stockholm") >>> _ensure_datetime_tzinfo(datetime(2015, 1, 1, 13, 15, tzinfo=UTC), tzinfo=tz).hour 14 :param datetime: Datetime to augment. :param tzinfo: Optional tznfo. :return: datetime with tzinfo :rtype: datetime """ if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=UTC) if tzinfo is not None: datetime = datetime.astimezone(get_timezone(tzinfo)) if hasattr(tzinfo, 'normalize'): # pytz datetime = tzinfo.normalize(datetime) return datetime
Example #9
Source File: dates.py From pySINDy with MIT License | 5 votes |
def _get_time(time, tzinfo=None): """ Get a timezoned time from a given instant. .. warning:: The return values of this function may depend on the system clock. :param time: time, datetime or None :rtype: time """ if time is None: time = datetime.utcnow() elif isinstance(time, number_types): time = datetime.utcfromtimestamp(time) if time.tzinfo is None: time = time.replace(tzinfo=UTC) if isinstance(time, datetime): if tzinfo is not None: time = time.astimezone(tzinfo) if hasattr(tzinfo, 'normalize'): # pytz time = tzinfo.normalize(time) time = time.timetz() elif tzinfo is not None: time = time.replace(tzinfo=tzinfo) return time
Example #10
Source File: dates.py From pySINDy with MIT License | 5 votes |
def format_datetime(datetime=None, format='medium', tzinfo=None, locale=LC_TIME): r"""Return a date formatted according to the given pattern. >>> dt = datetime(2007, 4, 1, 15, 30) >>> format_datetime(dt, locale='en_US') u'Apr 1, 2007, 3:30:00 PM' For any pattern requiring the display of the time-zone, the third-party ``pytz`` package is needed to explicitly specify the time-zone: >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'), ... locale='fr_FR') u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale' >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz", ... tzinfo=get_timezone('US/Eastern'), locale='en') u'2007.04.01 AD at 11:30:00 EDT' :param datetime: the `datetime` object; if `None`, the current date and time is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param tzinfo: the timezone to apply to the time for display :param locale: a `Locale` object or a locale identifier """ datetime = _ensure_datetime_tzinfo(_get_datetime(datetime), tzinfo) locale = Locale.parse(locale) if format in ('full', 'long', 'medium', 'short'): return get_datetime_format(format, locale=locale) \ .replace("'", "") \ .replace('{0}', format_time(datetime, format, tzinfo=None, locale=locale)) \ .replace('{1}', format_date(datetime, format, locale=locale)) else: return parse_pattern(format).apply(datetime, locale)
Example #11
Source File: dates.py From pySINDy with MIT License | 5 votes |
def format_skeleton(skeleton, datetime=None, tzinfo=None, fuzzy=True, locale=LC_TIME): r"""Return a time and/or date formatted according to the given pattern. The skeletons are defined in the CLDR data and provide more flexibility than the simple short/long/medium formats, but are a bit harder to use. The are defined using the date/time symbols without order or punctuation and map to a suitable format for the given locale. >>> t = datetime(2007, 4, 1, 15, 30) >>> format_skeleton('MMMEd', t, locale='fr') u'dim. 1 avr.' >>> format_skeleton('MMMEd', t, locale='en') u'Sun, Apr 1' >>> format_skeleton('yMMd', t, locale='fi') # yMMd is not in the Finnish locale; yMd gets used u'1.4.2007' >>> format_skeleton('yMMd', t, fuzzy=False, locale='fi') # yMMd is not in the Finnish locale, an error is thrown Traceback (most recent call last): ... KeyError: yMMd After the skeleton is resolved to a pattern `format_datetime` is called so all timezone processing etc is the same as for that. :param skeleton: A date time skeleton as defined in the cldr data. :param datetime: the ``time`` or ``datetime`` object; if `None`, the current time in UTC is used :param tzinfo: the time-zone to apply to the time for display :param fuzzy: If the skeleton is not found, allow choosing a skeleton that's close enough to it. :param locale: a `Locale` object or a locale identifier """ locale = Locale.parse(locale) if fuzzy and skeleton not in locale.datetime_skeletons: skeleton = match_skeleton(skeleton, locale.datetime_skeletons) format = locale.datetime_skeletons[skeleton] return format_datetime(datetime, format, tzinfo, locale)
Example #12
Source File: datetimes.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def tzinfo(self): """ Alias for tz attribute """ return self.tz
Example #13
Source File: datetimes.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def _timezone(self): """ Comparable timezone both for pytz / dateutil""" return timezones.get_timezone(self.tzinfo)
Example #14
Source File: datetimes.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def _has_same_tz(self, other): zzone = self._timezone # vzone sholdn't be None if value is non-datetime like if isinstance(other, np.datetime64): # convert to Timestamp as np.datetime64 doesn't have tz attr other = Timestamp(other) vzone = timezones.get_timezone(getattr(other, 'tzinfo', '__no_tz__')) return zzone == vzone
Example #15
Source File: datetimes.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def indexer_at_time(self, time, asof=False): """ Select values at particular time of day (e.g. 9:30AM) Parameters ---------- time : datetime.time or string Returns ------- values_at_time : TimeSeries """ from dateutil.parser import parse if asof: raise NotImplementedError("'asof' argument is not supported") if isinstance(time, compat.string_types): time = parse(time).time() if time.tzinfo: # TODO raise NotImplementedError("argument 'time' with timezone info is " "not supported") time_micros = self._get_time_micros() micros = _time_to_micros(time) return (micros == time_micros).nonzero()[0]
Example #16
Source File: datetimes.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def _generate_regular_range(start, end, periods, offset): if isinstance(offset, Tick): stride = offset.nanos if periods is None: b = Timestamp(start).value # cannot just use e = Timestamp(end) + 1 because arange breaks when # stride is too large, see GH10887 e = (b + (Timestamp(end).value - b) // stride * stride + stride // 2 + 1) # end.tz == start.tz by this point due to _generate implementation tz = start.tz elif start is not None: b = Timestamp(start).value e = b + np.int64(periods) * stride tz = start.tz elif end is not None: e = Timestamp(end).value + stride b = e - np.int64(periods) * stride tz = end.tz else: raise ValueError("at least 'start' or 'end' should be specified " "if a 'period' is given.") data = np.arange(b, e, stride, dtype=np.int64) data = DatetimeIndex._simple_new(data, None, tz=tz) else: if isinstance(start, Timestamp): start = start.to_pydatetime() if isinstance(end, Timestamp): end = end.to_pydatetime() xdr = generate_range(start=start, end=end, periods=periods, offset=offset) dates = list(xdr) # utc = len(dates) > 0 and dates[0].tzinfo is not None data = tools.to_datetime(dates) return data
Example #17
Source File: datetimes.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def tzinfo(self): """ Alias for tz attribute """ return self.tz
Example #18
Source File: datetimes.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def _timezone(self): """ Comparable timezone both for pytz / dateutil""" return timezones.get_timezone(self.tzinfo)
Example #19
Source File: datetimes.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def _has_same_tz(self, other): zzone = self._timezone # vzone sholdn't be None if value is non-datetime like if isinstance(other, np.datetime64): # convert to Timestamp as np.datetime64 doesn't have tz attr other = Timestamp(other) vzone = timezones.get_timezone(getattr(other, 'tzinfo', '__no_tz__')) return zzone == vzone
Example #20
Source File: datetimes.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def indexer_at_time(self, time, asof=False): """ Select values at particular time of day (e.g. 9:30AM) Parameters ---------- time : datetime.time or string Returns ------- values_at_time : TimeSeries """ from dateutil.parser import parse if asof: raise NotImplementedError("'asof' argument is not supported") if isinstance(time, compat.string_types): time = parse(time).time() if time.tzinfo: # TODO raise NotImplementedError("argument 'time' with timezone info is " "not supported") time_micros = self._get_time_micros() micros = _time_to_micros(time) return (micros == time_micros).nonzero()[0]
Example #21
Source File: datetimes.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def _generate_regular_range(start, end, periods, offset): if isinstance(offset, Tick): stride = offset.nanos if periods is None: b = Timestamp(start).value # cannot just use e = Timestamp(end) + 1 because arange breaks when # stride is too large, see GH10887 e = (b + (Timestamp(end).value - b) // stride * stride + stride // 2 + 1) # end.tz == start.tz by this point due to _generate implementation tz = start.tz elif start is not None: b = Timestamp(start).value e = b + np.int64(periods) * stride tz = start.tz elif end is not None: e = Timestamp(end).value + stride b = e - np.int64(periods) * stride tz = end.tz else: raise ValueError("at least 'start' or 'end' should be specified " "if a 'period' is given.") data = np.arange(b, e, stride, dtype=np.int64) data = DatetimeIndex._simple_new(data, None, tz=tz) else: if isinstance(start, Timestamp): start = start.to_pydatetime() if isinstance(end, Timestamp): end = end.to_pydatetime() xdr = generate_range(start=start, end=end, periods=periods, offset=offset) dates = list(xdr) # utc = len(dates) > 0 and dates[0].tzinfo is not None data = tools.to_datetime(dates) return data
Example #22
Source File: datetimes.py From recruit with Apache License 2.0 | 5 votes |
def get_value(self, series, key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ if isinstance(key, datetime): # needed to localize naive datetimes if self.tz is not None: if key.tzinfo is not None: key = Timestamp(key).tz_convert(self.tz) else: key = Timestamp(key).tz_localize(self.tz) return self.get_value_maybe_box(series, key) if isinstance(key, time): locs = self.indexer_at_time(key) return series.take(locs) try: return com.maybe_box(self, Index.get_value(self, series, key), series, key) except KeyError: try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError, KeyError): pass try: return self.get_value_maybe_box(series, key) except (TypeError, ValueError, KeyError): raise KeyError(key)
Example #23
Source File: datetimes.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def get_value(self, series, key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ if isinstance(key, datetime): # needed to localize naive datetimes if self.tz is not None: if key.tzinfo is not None: key = Timestamp(key).tz_convert(self.tz) else: key = Timestamp(key).tz_localize(self.tz) return self.get_value_maybe_box(series, key) if isinstance(key, time): locs = self.indexer_at_time(key) return series.take(locs) try: return com.maybe_box(self, Index.get_value(self, series, key), series, key) except KeyError: try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError, KeyError): pass try: return self.get_value_maybe_box(series, key) except (TypeError, ValueError, KeyError): raise KeyError(key)
Example #24
Source File: index.py From Computable with MIT License | 5 votes |
def _naive_in_cache_range(start, end): if start is None or end is None: return False else: if start.tzinfo is not None or end.tzinfo is not None: return False return _in_range(start, end, _CACHE_START, _CACHE_END)
Example #25
Source File: index.py From Computable with MIT License | 5 votes |
def _generate_regular_range(start, end, periods, offset): if isinstance(offset, Tick): stride = offset.nanos if periods is None: b = Timestamp(start).value e = Timestamp(end).value e += stride - e % stride # end.tz == start.tz by this point due to _generate implementation tz = start.tz elif start is not None: b = Timestamp(start).value e = b + periods * stride tz = start.tz elif end is not None: e = Timestamp(end).value + stride b = e - periods * stride tz = end.tz else: raise NotImplementedError data = np.arange(b, e, stride, dtype=np.int64) data = DatetimeIndex._simple_new(data, None, tz=tz) else: if isinstance(start, Timestamp): start = start.to_pydatetime() if isinstance(end, Timestamp): end = end.to_pydatetime() xdr = generate_range(start=start, end=end, periods=periods, offset=offset) dates = list(xdr) # utc = len(dates) > 0 and dates[0].tzinfo is not None data = tools.to_datetime(dates) return data
Example #26
Source File: index.py From Computable with MIT License | 5 votes |
def indexer_at_time(self, time, asof=False): """ Select values at particular time of day (e.g. 9:30AM) Parameters ---------- time : datetime.time or string tz : string or pytz.timezone Time zone for time. Corresponding timestamps would be converted to time zone of the TimeSeries Returns ------- values_at_time : TimeSeries """ from dateutil.parser import parse if asof: raise NotImplementedError if isinstance(time, compat.string_types): time = parse(time).time() if time.tzinfo: # TODO raise NotImplementedError time_micros = self._get_time_micros() micros = _time_to_micros(time) return (micros == time_micros).nonzero()[0]
Example #27
Source File: datetimes.py From recruit with Apache License 2.0 | 5 votes |
def indexer_at_time(self, time, asof=False): """ Returns index locations of index values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or string datetime.time or string in appropriate format ("%H:%M", "%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p", "%I%M%S%p"). Returns ------- values_at_time : array of integers See Also -------- indexer_between_time, DataFrame.at_time """ from dateutil.parser import parse if asof: raise NotImplementedError("'asof' argument is not supported") if isinstance(time, compat.string_types): time = parse(time).time() if time.tzinfo: # TODO raise NotImplementedError("argument 'time' with timezone info is " "not supported") time_micros = self._get_time_micros() micros = _time_to_micros(time) return (micros == time_micros).nonzero()[0]
Example #28
Source File: index.py From Computable with MIT License | 5 votes |
def tzinfo(self): """ Alias for tz attribute """ return self.tz
Example #29
Source File: datetimes.py From vnpy_crypto with MIT License | 5 votes |
def tzinfo(self): """ Alias for tz attribute """ return self.tz
Example #30
Source File: dates.py From sndlatr with Apache License 2.0 | 5 votes |
def __init__(self, value, locale): assert isinstance(value, (date, datetime, time)) if isinstance(value, (datetime, time)) and value.tzinfo is None: value = value.replace(tzinfo=UTC) self.value = value self.locale = Locale.parse(locale)