Python datetime.datetime.timezone() Examples

The following are code examples for showing how to use datetime.datetime.timezone(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: chat   Author: cambridgeltl   File: tardis.py    (license) View Source Project 6 votes vote down vote up
def __repr__(self):
        """Convert to formal string, for repr().

        >>> tz = timezone.utc
        >>> repr(tz)
        'datetime.timezone.utc'
        >>> tz = timezone(timedelta(hours=-5), 'EST')
        >>> repr(tz)
        "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')"
        """
        if self is self.utc:
            return 'datetime.timezone.utc'
        if self._name is None:
            return "%s(%r)" % ('datetime.' + self.__class__.__name__,
                               self._offset)
        return "%s(%r, %r)" % ('datetime.' + self.__class__.__name__,
                               self._offset, self._name) 
Example 2
Project: chat   Author: cambridgeltl   File: tardis.py    (license) View Source Project 6 votes vote down vote up
def __repr__(self):
        """Convert to formal string, for repr().

        >>> tz = timezone.utc
        >>> repr(tz)
        'datetime.timezone.utc'
        >>> tz = timezone(timedelta(hours=-5), 'EST')
        >>> repr(tz)
        "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')"
        """
        if self is self.utc:
            return 'datetime.timezone.utc'
        if self._name is None:
            return "%s(%r)" % ('datetime.' + self.__class__.__name__,
                               self._offset)
        return "%s(%r, %r)" % ('datetime.' + self.__class__.__name__,
                               self._offset, self._name) 
Example 3
Project: ibstract   Author: jesseliu0   File: marketdata.py    (license) View Source Project 5 votes vote down vote up
def TimeEnd(self, timeend):
        if timeend is None:
            self._timeend = datetime.now(tz=pytz.utc)
        elif not isinstance(timeend, datetime):
            raise TypeError("req.TimeEnd must be a datetime.datetime object.")
        else:
            # Always use timezone-aware datetime.
            if timeend.tzinfo is None:
                _logger.warning('Naive HistDataReq.TimeEnd. '
                                'Assumeing system local time zone.')
                tz_system = get_localzone()
                timeend = tz_system.localize(timeend)
            self._timeend = timeend 
Example 4
Project: chat   Author: cambridgeltl   File: tardis.py    (license) View Source Project 5 votes vote down vote up
def __eq__(self, other):
        if type(other) != timezone:
            return False
        return self._offset == other._offset 
Example 5
Project: chat   Author: cambridgeltl   File: tardis.py    (license) View Source Project 5 votes vote down vote up
def __eq__(self, other):
        if type(other) != timezone:
            return False
        return self._offset == other._offset 
Example 6
Project: kytos   Author: kytos   File: helpers.py    (license) View Source Project 5 votes vote down vote up
def now(tzone=timezone.utc):
    """Return the current datetime (default to UTC).

    Args:
        tzone (datetime.timezone): Specific time zone used in datetime.

    Returns:
        datetime.datetime.now: Date time with specific time zone.

    """
    return datetime.now(tzone) 
Example 7
Project: django-anymail   Author: anymail   File: utils.py    (license) View Source Project 5 votes vote down vote up
def parsedate_to_datetime(s):
        # *dtuple, tz = _parsedate_tz(data)
        dtuple = parsedate_tz(s)
        tz = dtuple[-1]
        # if tz is None:  # parsedate_tz returns 0 for "-0000"
        if tz is None or (tz == 0 and "-0000" in s):
            # "... indicates that the date-time contains no information
            # about the local time zone" (RFC 2822 #3.3)
            return datetime(*dtuple[:6])
        else:
            # tzinfo = datetime.timezone(datetime.timedelta(seconds=tz))  # Python 3.2+ only
            tzinfo = get_fixed_timezone(tz // 60)  # don't use timedelta (avoid Django bug #28739)
            return datetime(*dtuple[:6], tzinfo=tzinfo) 
Example 8
Project: django-anymail   Author: anymail   File: utils.py    (license) View Source Project 5 votes vote down vote up
def parse_rfc2822date(s):
    """Parses an RFC-2822 formatted date string into a datetime.datetime

    Returns None if string isn't parseable. Returned datetime will be naive
    if string doesn't include known timezone offset; aware if it does.

    (Same as Python 3 email.utils.parsedate_to_datetime, with improved
    handling for unparseable date strings.)
    """
    try:
        return parsedate_to_datetime(s)
    except (IndexError, TypeError, ValueError):
        # despite the docs, parsedate_to_datetime often dies on unparseable input
        return None 
Example 9
Project: arq   Author: samuelcolvin   File: utils.py    (license) View Source Project 5 votes vote down vote up
def create_tz(utcoffset=0) -> timezone:
    """
    Create a python datetime.timezone with a given utc offset.

    :param utcoffset: utc offset in seconds, if 0 timezone.utc is returned.
    """
    if utcoffset == 0:
        return timezone.utc
    else:
        return timezone(timedelta(seconds=utcoffset)) 
Example 10
Project: arq   Author: samuelcolvin   File: utils.py    (license) View Source Project 5 votes vote down vote up
def to_unix_ms_tz(dt: datetime) -> Tuple[int, Union[int, None]]:
    """
    convert a datetime to number of milliseconds since 1970 and calculate timezone offset
    :param dt: datetime to evaluate
    :return: tuple - (unix time in milliseconds, utc offset in seconds)
    """
    utcoffset = dt.utcoffset()
    if utcoffset is not None:
        _utcoffset = utcoffset.total_seconds()
        unix = (dt - EPOCH_TZ).total_seconds() + _utcoffset
        return int(unix * 1000), int(_utcoffset)
    else:
        return int((dt - EPOCH).total_seconds() * 1000), None 
Example 11
Project: arq   Author: samuelcolvin   File: utils.py    (license) View Source Project 5 votes vote down vote up
def from_unix_ms(ms: int, utcoffset: int=None) -> datetime:
    """
    convert int to a datetime.

    :param ms: number of milliseconds since 1970
    :param utcoffset: if set a timezone i added to the datime based on the offset in seconds.
    :return: datetime - including timezone if utcoffset is not None, else timezone naïve
    """
    dt = EPOCH + timedelta(milliseconds=ms)
    if utcoffset is not None:
        dt = dt.replace(tzinfo=create_tz(utcoffset))
    return dt 
Example 12
Project: ibstract   Author: jesseliu0   File: marketdata.py    (license) View Source Project 4 votes vote down vote up
def _standardize_index(
            self, df_in: pd.DataFrame, symbol: str=None, datatype: str=None,
            barsize: str=None, tz: str=None):
        """Normalize input DataFrame index to MarketDataBlock standard.
        """
        # Add or starndardize index names in the input.
        if isinstance(df_in.index, pd.MultiIndex):
            df_in.reset_index(inplace=True)

        # Rename ambiguous column names.
        df_in.columns = [
            col_rename.get(col.strip().lower(), col.strip().lower())
            for col in df_in.columns]

        # Insert Symbol, DataType, Barsize columns from arguments if not
        # found in the input dataframe.
        for col in MarketDataBlock.data_index:
            if col not in df_in.columns:
                if locals().get(col.lower(), None) is None:
                    raise KeyError(
                        'No {0} argument and no {0} column in the DataFrame.'
                        .format(col))
                df_in.insert(0, col, locals()[col.lower()])

        # Convert datetime strings to pandas DatetimeIndex
        df_in['TickerTime'] = pd.DatetimeIndex(
            df_in['TickerTime'].apply(pd.Timestamp))

        # Standardize BarSize strings
        df_in['BarSize'] = df_in['BarSize'].map(timedur_standardize)

        # Set index to class-defined MultiIndex
        df_in.set_index(MarketDataBlock.data_index, inplace=True)

        # Set time zone so all DatetimeIndex are tz-aware
        df_in_tz = df_in.index.levels[self.__class__.dtlevel].tz
        if df_in_tz is None or isinstance(df_in_tz, timezone) or \
           isinstance(df_in_tz, pytz._FixedOffset):
            # Input df has naive time index, or tzinfo is not pytz.timezone()
            if tz is None:
                raise ValueError(
                    'Argument tz=None, and TickerTime.tzinfo is None(naive),'
                    'datetime.timezone, or pytz._FixedOffset.')
            if df_in_tz is None:
                df_in = df_in.tz_localize(tz, level=self.__class__.dtlevel)
            else:
                df_in = df_in.tz_convert(tz, level=self.__class__.dtlevel)

        return df_in