Python datetime.datetime.replace() Examples

The following are code examples for showing how to use datetime.datetime.replace(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pongr   Author: wseaton   File: run.py    MIT License 6 votes vote down vote up
def matches():
    singles = pd.read_sql('select * from game where deleted = 0', con=engine)
    doubles = pd.read_sql('select * from doubles_game where deleted = 0', con=engine)

    tz = pytz.timezone('America/New_York')

    for frame in [singles, doubles]:

        frame['timestamp'] = frame['timestamp'].apply(datetime.utcfromtimestamp)
        frame['timestamp'] = frame['timestamp'].apply(datetime.replace, tzinfo=tz)
        frame['timestamp'] = frame['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S %Z')

    singles = singles.to_dict('records')
    doubles = doubles.to_dict('records')

    return render_template('gamelog.html', singles_games=singles, doubles_games=doubles) 
Example 2
Project: pongr   Author: wseaton   File: run.py    MIT License 6 votes vote down vote up
def push_new_doubles_ratings(con=None):
    """
    recalculates doubles ratings and pushes them to the database
    """
    games = pd.read_sql('select * from doubles_game where deleted = 0', con=con)

    ratingdf = calculate_doubles_ratings(games)
    ratingdf = (ratingdf.reset_index().rename(columns={'index':'alias'})
                .drop('level_0', axis=1))

    ratingdf.to_sql('doubles_ratings', con=con, if_exists='replace', index=False)

    team_ratingdf = calculate_team_ratings(games)
    team_ratingdf = (team_ratingdf.reset_index().rename(columns={'index': 'team'})
                .drop('level_0', axis=1))

    team_ratingdf.to_sql('team_doubles_ratings', con=con, if_exists='replace', index=False) 
Example 3
Project: Rovers   Author: RIT-Space-Exploration   File: dates.py    MIT License 6 votes vote down vote up
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 4
Project: Rovers   Author: RIT-Space-Exploration   File: dates.py    MIT License 6 votes vote down vote up
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 5
Project: Rovers   Author: RIT-Space-Exploration   File: dates.py    MIT License 6 votes vote down vote up
def untokenize_pattern(tokens):
    """
    Turn a date format pattern token stream back into a string.

    This is the reverse operation of ``tokenize_pattern``.

    :type tokens: Iterable[tuple]
    :rtype: str
    """
    output = []
    for tok_type, tok_value in tokens:
        if tok_type == "field":
            output.append(tok_value[0] * tok_value[1])
        elif tok_type == "chars":
            if not any(ch in PATTERN_CHARS for ch in tok_value):  # No need to quote
                output.append(tok_value)
            else:
                output.append("'%s'" % tok_value.replace("'", "''"))
    return "".join(output) 
Example 6
Project: pySINDy   Author: luckystarufo   File: dates.py    MIT License 6 votes vote down vote up
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 7
Project: pySINDy   Author: luckystarufo   File: dates.py    MIT License 6 votes vote down vote up
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 8
Project: pySINDy   Author: luckystarufo   File: dates.py    MIT License 6 votes vote down vote up
def untokenize_pattern(tokens):
    """
    Turn a date format pattern token stream back into a string.

    This is the reverse operation of ``tokenize_pattern``.

    :type tokens: Iterable[tuple]
    :rtype: str
    """
    output = []
    for tok_type, tok_value in tokens:
        if tok_type == "field":
            output.append(tok_value[0] * tok_value[1])
        elif tok_type == "chars":
            if not any(ch in PATTERN_CHARS for ch in tok_value):  # No need to quote
                output.append(tok_value)
            else:
                output.append("'%s'" % tok_value.replace("'", "''"))
    return "".join(output) 
Example 9
Project: myBlog   Author: adxc   File: dates.py    MIT License 6 votes vote down vote up
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
Project: myBlog   Author: adxc   File: dates.py    MIT License 6 votes vote down vote up
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 11
Project: myBlog   Author: adxc   File: dates.py    MIT License 6 votes vote down vote up
def untokenize_pattern(tokens):
    """
    Turn a date format pattern token stream back into a string.

    This is the reverse operation of ``tokenize_pattern``.

    :type tokens: Iterable[tuple]
    :rtype: str
    """
    output = []
    for tok_type, tok_value in tokens:
        if tok_type == "field":
            output.append(tok_value[0] * tok_value[1])
        elif tok_type == "chars":
            if not any(ch in PATTERN_CHARS for ch in tok_value):  # No need to quote
                output.append(tok_value)
            else:
                output.append("'%s'" % tok_value.replace("'", "''"))
    return "".join(output) 
Example 12
Project: wazuh-qa   Author: wazuh   File: tools.py    GNU General Public License v2.0 6 votes vote down vote up
def expand_placeholders(mutable_obj, placeholders=None):
    """Search for placeholders and replace them by a value inside mutable_obj

    :param mutable_obj: target object where the replacement are performed
    :param placeholders: dict where each key is a placeholder and the value is the replacement
    :return: reference to mutable_obj
    """
    placeholders = {} if placeholders is None else placeholders
    if isinstance(mutable_obj, list):
        for criterion, placeholder in placeholders.items():
            for index, value in enumerate(mutable_obj):
                if value == criterion:
                    mutable_obj[index] = placeholder
                elif isinstance(value, (dict, list)):
                    expand_placeholders(mutable_obj[index], placeholders=placeholders)
    elif isinstance(mutable_obj, dict):
        for criterion, placeholder in placeholders.items():
            for key, value in mutable_obj.items():
                if criterion == value:
                    mutable_obj[key] = placeholder
                elif isinstance(value, (dict, list)):
                    expand_placeholders(mutable_obj[key], placeholders=placeholders)

    return mutable_obj 
Example 13
Project: wazuh-qa   Author: wazuh   File: tools.py    GNU General Public License v2.0 6 votes vote down vote up
def reformat_time(scan_time):
    """ Transform scan_time to readable time

    :param scan_time: Time string
    :type scan_time: String
    :return: Datetime object
    """
    hour_format = '%H'
    colon = ''
    locale = ''
    if ':' in scan_time:
        colon = ':%M'
    if re.search('[a-zA-Z]', scan_time):
        locale = '%p'
        hour_format = '%I'
    cd = datetime.now()
    return datetime.replace(datetime.strptime(scan_time, hour_format + colon + locale),
                            year=cd.year, month=cd.month, day=cd.day) 
Example 14
Project: wazuh-qa   Author: wazuh   File: test_scan_day_and_time.py    GNU General Public License v2.0 6 votes vote down vote up
def replace_date(date, days):
    """ Adds a number of days to the given date and calculates if it should change the month as well.

    :param date: Datetime with a date
    :param days: Integer with a number of days
    :return: Datetime with the new date
    """
    today = datetime.now()
    max_days_in_month = monthrange(today.year, today.month)[1]
    if today.day + days > max_days_in_month:
        new_day = (today.day + days) % max_days_in_month
        new_month = today.month + 1
    else:
        new_day = today.day + days
        new_month = today.month

    return datetime.replace(date, day=new_day, month=new_month)


# fixtures 
Example 15
Project: Light_control   Author: laurent-colas   File: dates.py    The Unlicense 6 votes vote down vote up
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 16
Project: Light_control   Author: laurent-colas   File: dates.py    The Unlicense 6 votes vote down vote up
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 17
Project: Light_control   Author: laurent-colas   File: dates.py    The Unlicense 6 votes vote down vote up
def untokenize_pattern(tokens):
    """
    Turn a date format pattern token stream back into a string.

    This is the reverse operation of ``tokenize_pattern``.

    :type tokens: Iterable[tuple]
    :rtype: str
    """
    output = []
    for tok_type, tok_value in tokens:
        if tok_type == "field":
            output.append(tok_value[0] * tok_value[1])
        elif tok_type == "chars":
            if not any(ch in PATTERN_CHARS for ch in tok_value):  # No need to quote
                output.append(tok_value)
            else:
                output.append("'%s'" % tok_value.replace("'", "''"))
    return "".join(output) 
Example 18
Project: plataforma-livre-dados-abertos   Author: pbaesse   File: dates.py    GNU General Public License v3.0 6 votes vote down vote up
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 19
Project: pongr   Author: wseaton   File: run.py    MIT License 5 votes vote down vote up
def push_new_ratings(con=None):
    """
    recalculates player ratings and pushes them to the database
    """
    games = pd.read_sql('select * from game where deleted = 0', con=con)

    ratingdf = calculate_ratings(games)
    ratingdf = (ratingdf.reset_index().rename(columns={'index':'alias'})
                .drop('level_0', axis=1))

    ratingdf.to_sql('ratings', con=con, if_exists='replace', index=False) 
Example 20
Project: sndlatr   Author: Schibum   File: dates.py    Apache License 2.0 5 votes vote down vote up
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) 
Example 21
Project: sndlatr   Author: Schibum   File: dates.py    Apache License 2.0 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 22
Project: DroidPot   Author: WhySoGeeky   File: dates.py    MIT License 5 votes vote down vote up
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) 
Example 23
Project: DroidPot   Author: WhySoGeeky   File: dates.py    MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 24
Project: xuemc   Author: skycucumber   File: dates.py    GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 25
Project: xuemc   Author: skycucumber   File: dates.py    GNU General Public License v2.0 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 26
Project: ton_client   Author: formony   File: client.py    Mozilla Public License 2.0 5 votes vote down vote up
def wallet_send_grams(self, public_key, secret, dest_address, seq_no: int, valid_until: datetime, amount, message=''):
        """
        TL Spec
            wallet.sendGrams private_key:inputKey destination:accountAddress seqno:int32 valid_until:int53 amount:int64 message:bytes
                = SendGramsResult;
            inputKey key:key local_password:secureBytes = InputKey;
            key public_key:string secret:secureBytes = Key;
            accountAddress account_address:string = AccountAddress;
            sendGramsResult sent_until:int53 = SendGramsResult;
        :param public_key:
        :param secret:
        :param dest_address:
        :param seq_no:
        :param valid_until:
        :param amount:
        :param message:
        :return:
        """
        if valid_until.tzname() is None:
            valid_until = datetime.replace(tzinfo=timezone.utc)
        valid_until_ts = valid_until.timestamp()

        data = {
            '@type': 'wallet.sendGrams',
            'private_key': {
                'key': {
                    'public_key': public_key,
                    'secret': secret
                }
            },
            'destination': {
                'account_address': dest_address
            },
            'seqno': seq_no,
            'valid_until': valid_until_ts,
            'amount': amount,
            'message': message
        }

        r = self._t_local.tonlib.ton_async_execute(data)
        return r 
Example 27
Project: badger-api   Author: 2gis   File: tasks.py    MIT License 5 votes vote down vote up
def update_state(bug):
    log.debug('Starting bug "{}" update'.format(bug.externalId))
    now = datetime.utcnow()
    td = now - datetime.replace(bug.updated, tzinfo=None)
    diff = (td.microseconds +
            (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

    if bug.state in settings.BUG_STATE_EXPIRED:
        old_state = bug.state
        new_state = \
            get_issue_fields_from_bts(bug.externalId)['status']['name']
        log.debug('Comparing bug state,'
                  '"{0}" and "{1}"'.format(old_state, new_state))
        if old_state == new_state and diff > float(settings.BUG_TIME_EXPIRED):
            log.debug(
                'Bug "{}" expired, deleting it from DB'.format(bug.externalId))
            bug.delete()
        elif old_state == new_state \
                and diff < float(settings.BUG_TIME_EXPIRED):
            log.debug(
                'Bug "{}" not updated, '
                'because {} seconds not expired'.format(
                    bug.externalId, settings.BUG_TIME_EXPIRED))
        else:
            bug.state = new_state
            bug.updated = now
            log.debug('Saving bug "{}"'.format(bug.externalId))
            bug.save()
    if bug.state not in settings.BUG_STATE_EXPIRED \
            and diff > float(settings.TIME_BEFORE_UPDATE_BUG_INFO):
        log.debug("%s > %s time to update bug state.", diff,
                  settings.TIME_BEFORE_UPDATE_BUG_INFO)
        bug.updated = now
        bug.state = \
            get_issue_fields_from_bts(bug.externalId)['status']['name']
        log.debug('Saving bug "{}"'.format(bug.externalId))
        bug.save() 
Example 28
Project: Rovers   Author: RIT-Space-Exploration   File: dates.py    MIT License 5 votes vote down vote up
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 29
Project: Rovers   Author: RIT-Space-Exploration   File: dates.py    MIT License 5 votes vote down vote up
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 30
Project: Rovers   Author: RIT-Space-Exploration   File: dates.py    MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 31
Project: pySINDy   Author: luckystarufo   File: dates.py    MIT License 5 votes vote down vote up
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 32
Project: pySINDy   Author: luckystarufo   File: dates.py    MIT License 5 votes vote down vote up
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 33
Project: pySINDy   Author: luckystarufo   File: dates.py    MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 34
Project: course-activity-planner   Author: fuhrmanator   File: interpreter.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_new_datetime(self, datetime, relative_mod, time_mod):
        """Build new datetime from relative and time modifiers."""
        if relative_mod:
            datetime += relative_mod

        if time_mod:
            return datetime.replace(hour=time_mod.hour, minute=time_mod.minute)

        return datetime 
Example 35
Project: myBlog   Author: adxc   File: dates.py    MIT License 5 votes vote down vote up
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 36
Project: myBlog   Author: adxc   File: dates.py    MIT License 5 votes vote down vote up
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 37
Project: myBlog   Author: adxc   File: dates.py    MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 38
Project: myBlog   Author: adxc   File: __init__.py    MIT License 5 votes vote down vote up
def to_user_timezone(datetime):
    """Convert a datetime object to the user's timezone.  This automatically
    happens on all date formatting unless rebasing is disabled.  If you need
    to convert a :class:`datetime.datetime` object at any time to the user's
    timezone (as returned by :func:`get_timezone` this function can be used).
    """
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    tzinfo = get_timezone()
    return tzinfo.normalize(datetime.astimezone(tzinfo)) 
Example 39
Project: myBlog   Author: adxc   File: __init__.py    MIT License 5 votes vote down vote up
def to_utc(datetime):
    """Convert a datetime object to UTC and drop tzinfo.  This is the
    opposite operation to :func:`to_user_timezone`.
    """
    if datetime.tzinfo is None:
        datetime = get_timezone().localize(datetime)
    return datetime.astimezone(UTC).replace(tzinfo=None) 
Example 40
Project: andris-projeto   Author: andris210296   File: dates.py    MIT License 5 votes vote down vote up
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) 
Example 41
Project: andris-projeto   Author: andris210296   File: dates.py    MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 42
Project: andris-projeto   Author: andris210296   File: dates.py    MIT License 5 votes vote down vote up
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) 
Example 43
Project: andris-projeto   Author: andris210296   File: dates.py    MIT License 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 44
Project: wazuh-qa   Author: wazuh   File: tools.py    GNU General Public License v2.0 5 votes vote down vote up
def set_section_wazuh_conf(section: str = 'syscheck',
                           new_elements: List = None) -> ET.ElementTree:
    """Set a configuration in a section of Wazuh. It replaces the content if it exists.
    :param section: Section of Wazuh configuration to replace
    :param new_elements: List with dictionaries for settings elements in the section
    :return: ElementTree with the custom Wazuh configuration
    """

    def create_elements(section: ET.Element, elements: List):
        """Insert new elements in a Wazuh configuration section.

        :param section: Section where the element will be inserted
        :param elements: List with the new elements to be inserted
        """
        for element in elements:
            for tag_name, properties in element.items():
                tag = ET.SubElement(section, tag_name)
                new_elements = properties.get('elements')
                if new_elements:
                    create_elements(tag, new_elements)
                else:
                    tag.text = str(properties.get('value'))
                    attributes = properties.get('attributes')
                    if attributes:
                        for attribute in attributes:
                            if attribute is not None and isinstance(attribute, dict):  # noqa: E501
                                for attr_name, attr_value in attribute.items():
                                    tag.attrib[attr_name] = str(attr_value)
    # get Wazuh configuration
    wazuh_conf = get_wazuh_conf()
    section_conf = wazuh_conf.find(section)
    # create section if it does not exist, clean otherwise
    if not section_conf:
        section_conf = ET.SubElement(wazuh_conf.getroot(), section)
    else:
        section_conf.clear()
    # insert elements
    if new_elements:
        create_elements(section_conf, new_elements)
    return wazuh_conf 
Example 45
Project: pipa-pay-server   Author: davidvon   File: dates.py    Apache License 2.0 5 votes vote down vote up
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) 
Example 46
Project: pipa-pay-server   Author: davidvon   File: dates.py    Apache License 2.0 5 votes vote down vote up
def get_day_of_year(self, date=None):
        if date is None:
            date = self.value
        return (date - date.replace(month=1, day=1)).days + 1 
Example 47
Project: pipa-pay-server   Author: davidvon   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def to_utc(datetime):
    """Convert a datetime object to UTC and drop tzinfo.  This is the
    opposite operation to :func:`to_user_timezone`.
    """
    if datetime.tzinfo is None:
        datetime = get_timezone().localize(datetime)
    return datetime.astimezone(UTC).replace(tzinfo=None) 
Example 48
Project: pipa-pay-server   Author: davidvon   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def to_user_timezone(datetime):
    """Convert a datetime object to the user's timezone.  This automatically
    happens on all date formatting unless rebasing is disabled.  If you need
    to convert a :class:`datetime.datetime` object at any time to the user's
    timezone (as returned by :func:`get_timezone` this function can be used).
    """
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=UTC)
    tzinfo = get_timezone()
    return tzinfo.normalize(datetime.astimezone(tzinfo)) 
Example 49
Project: pipa-pay-server   Author: davidvon   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def to_utc(datetime):
    """Convert a datetime object to UTC and drop tzinfo.  This is the
    opposite operation to :func:`to_user_timezone`.
    """
    if datetime.tzinfo is None:
        datetime = get_timezone().localize(datetime)
    return datetime.astimezone(UTC).replace(tzinfo=None) 
Example 50
Project: Light_control   Author: laurent-colas   File: dates.py    The Unlicense 5 votes vote down vote up
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