Python datetime.timezone() Examples

The following are 30 code examples for showing how to use datetime.timezone(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: ciso8601   Author: closeio   File: tests.py    License: MIT License 6 votes vote down vote up
def test_invalid_tz_offsets_too_large(self):
        # The Python interpreter crashes if you give the datetime constructor a TZ offset with an absolute value >= 1440
        # TODO: Determine whether these are valid ISO 8601 values and therefore whether ciso8601 should support them.
        self.assertRaisesRegex(
            ValueError,
            # Error message differs whether or not we are using pytz or datetime.timezone
            r"^offset must be a timedelta strictly between" if sys.version_info.major >= 3 else r"\('absolute offset is too large', -5940\)",
            ciso8601.parse_datetime,
            '2018-01-01T00:00:00.00-99',
        )

        self.assertRaisesRegex(
            ValueError,
            r"tzminute must be in 0..59",
            ciso8601.parse_datetime,
            '2018-01-01T00:00:00.00-23:60',
        ) 
Example 2
Project: rets   Author: opendoor-labs   File: decoder_test.py    License: MIT License 6 votes vote down vote up
def test_decode_time():
    assert _decode_time('03:04:05', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    # TODO: The standard specifies that the second fraction is limited to one
    # digit, however udatetime only permits 3 or 6 digits.
    assert _decode_time('03:04:05.600', True) == time(3, 4, 5, 600000, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05Z', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05+00:00', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05-00:00', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05+07:08', True) == time(3, 4, 5, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_time('03:04:05-07:08', True) == time(3, 4, 5, tzinfo=timezone(timedelta(hours=-7, minutes=-8)))
    assert _decode_time('03:04:05.600+07:08', True) == \
           time(3, 4, 5, 600000, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_time('03:04:05', False) == time(3, 4, 5)
    assert _decode_time('03:04:05.600', False) == time(3, 4, 5, 600000)
    assert _decode_time('03:04:05Z', False) == time(3, 4, 5)
    assert _decode_time('03:04:05+00:00', False) == time(3, 4, 5)
    assert _decode_time('03:04:05-00:00', False) == time(3, 4, 5)
    assert _decode_time('12:00:00+07:08', False) == time(4, 52)
    assert _decode_time('12:00:00-07:08', False) == time(19, 8) 
Example 3
Project: KubeOperator   Author: KubeOperator   File: cluster_backup_utils.py    License: Apache License 2.0 6 votes vote down vote up
def upload_backup_file(project_id,backup_storage_id):
    cluster = Cluster.objects.get(id=project_id)
    backup_storage = BackupStorage.objects.get(id=backup_storage_id)
    now =datetime.now().astimezone(timezone(timedelta(hours=8))).strftime('%Y-%m-%d %H:%M:%S')
    client = StorageClient(backup_storage)
    client.check_valid()
    file_name = cluster.name+'-'+str(now)+'.zip'
    file_remote_path = cluster.name+'/'+file_name
    result,message = client.upload_file("/etc/ansible/roles/cluster-backup/files/cluster-backup.zip",file_remote_path)
    if result:
        clusterBackup = ClusterBackup(name=file_name,size=10,folder=file_remote_path,
                                      backup_storage_id=backup_storage_id,project_id=project_id)
        clusterBackup.save()
        return True
    else:
        return False 
Example 4
Project: pipenv   Author: pypa   File: iso8601.py    License: MIT License 6 votes vote down vote up
def parse_timezone(matches, default_timezone=UTC):
    """Parses ISO 8601 time zone specs into tzinfo offsets

    """

    if matches["timezone"] == "Z":
        return UTC
    # This isn't strictly correct, but it's common to encounter dates without
    # timezones so I'll assume the default (which defaults to UTC).
    # Addresses issue 4.
    if matches["timezone"] is None:
        return default_timezone
    sign = matches["tz_sign"]
    hours = to_int(matches, "tz_hour")
    minutes = to_int(matches, "tz_minute", default_to_zero=True)
    description = "%s%02d:%02d" % (sign, hours, minutes)
    if sign == "-":
        hours = -hours
        minutes = -minutes
    return FixedOffset(hours, minutes, description) 
Example 5
Project: pvlib-python   Author: pvlib   File: location.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, latitude, longitude, tz='UTC', altitude=0,
                 name=None, **kwargs):

        self.latitude = latitude
        self.longitude = longitude

        if isinstance(tz, str):
            self.tz = tz
            self.pytz = pytz.timezone(tz)
        elif isinstance(tz, datetime.timezone):
            self.tz = 'UTC'
            self.pytz = pytz.UTC
        elif isinstance(tz, datetime.tzinfo):
            self.tz = tz.zone
            self.pytz = tz
        elif isinstance(tz, (int, float)):
            self.tz = tz
            self.pytz = pytz.FixedOffset(tz*60)
        else:
            raise TypeError('Invalid tz specification')

        self.altitude = altitude

        self.name = name 
Example 6
Project: osxphotos   Author: RhetTbull   File: test_mojave_10_14_5.py    License: MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["15uNd7%8RguTEgNPKHfTWw"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "Pumkins2.jpg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert p.albums == ["Pumpkin Farm"]
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "/tests/Test-10.14.5.photoslibrary/Masters/2019/07/27/20190727-131650/Pumkins2.jpg"
    )
    assert p.ismissing == False 
Example 7
Project: osxphotos   Author: RhetTbull   File: test_catalina_10_15_1.py    License: MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["D79B8D77-BFFC-460B-9312-034F2877D35B"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "D79B8D77-BFFC-460B-9312-034F2877D35B.jpeg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert sorted(p.albums) == ["Multi Keyword", "Pumpkin Farm", "Test Album"]
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "tests/Test-10.15.1.photoslibrary/originals/D/D79B8D77-BFFC-460B-9312-034F2877D35B.jpeg"
    )
    assert p.ismissing == False 
Example 8
Project: osxphotos   Author: RhetTbull   File: test_10_12_6.py    License: MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["sE5LlfekS8ykEE7o0cuMVA"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "Pumkins2.jpg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert sorted(p.albums) == ["AlbumInFolder", "Pumpkin Farm"]
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "/tests/Test-10.12.6.photoslibrary/Masters/2019/08/24/20190824-030824/Pumkins2.jpg"
    )
    assert p.ismissing == False 
Example 9
Project: osxphotos   Author: RhetTbull   File: test_mojave_10_14_6.py    License: MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["15uNd7%8RguTEgNPKHfTWw"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "Pumkins2.jpg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert sorted(p.albums) == sorted(
        ["Pumpkin Farm", "AlbumInFolder", "Test Album (1)"]
    )
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "/tests/Test-10.14.6.photoslibrary/Masters/2019/07/27/20190727-131650/Pumkins2.jpg"
    )
    assert p.ismissing == False 
Example 10
Project: osxphotos   Author: RhetTbull   File: test_catalina_10_15_4.py    License: MIT License 6 votes vote down vote up
def test_attributes():
    import datetime
    import osxphotos

    photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
    photos = photosdb.photos(uuid=["D79B8D77-BFFC-460B-9312-034F2877D35B"])
    assert len(photos) == 1
    p = photos[0]
    assert p.keywords == ["Kids"]
    assert p.original_filename == "Pumkins2.jpg"
    assert p.filename == "D79B8D77-BFFC-460B-9312-034F2877D35B.jpeg"
    assert p.date == datetime.datetime(
        2018, 9, 28, 16, 7, 7, 0, datetime.timezone(datetime.timedelta(seconds=-14400))
    )
    assert p.description == "Girl holding pumpkin"
    assert p.title == "I found one!"
    assert sorted(p.albums) == ["Pumpkin Farm", "Test Album"]
    assert p.persons == ["Katie"]
    assert p.path.endswith(
        "tests/Test-10.15.4.photoslibrary/originals/D/D79B8D77-BFFC-460B-9312-034F2877D35B.jpeg"
    )
    assert p.ismissing == False 
Example 11
Project: AmbroBot   Author: Ambro17   File: commands.py    License: GNU General Public License v3.0 6 votes vote down vote up
def retro_add(bot, update, args):
    if not args:
        update.message.reply_text(
            'Tenes que agregar algo al retro bucket. `/retro mas recursos`',
            parse_mode='markdown',
        )
        return
    retro_item = ' '.join(args)
    user = update.effective_user.first_name
    buenos_aires_offset = timezone(timedelta(hours=GMT_BUENOS_AIRES))
    date = d.now(buenos_aires_offset)
    save_retro_item(retro_item, user, date)
    update.message.reply_text(
        '✅ Listo. Tu mensaje fue guardado para la retro.\n'
        'Para recordarlo en la retro escribí `/retroitems`',
        parse_mode='markdown',
    )
    logger.info("Retro event added: %s %s %s", user, retro_item, date) 
Example 12
Project: authenticator   Author: JeNeSuisPasDave   File: data.py    License: MIT License 6 votes vote down vote up
def incremented_count(self):
        """Increment the counter and return the new value.

        Will update last_count() and last_count_update_time() properties.

        Only relevant if counter_from_time() is True.

        Returns:
            The incremented last_count value.

        """
        from datetime import datetime

        self.__last_count += 1

        # get the local time, with timezone
        #
        now = datetime.now(ClientData.tz())
        self.set_last_count_update_time(now)
        return self.last_count() 
Example 13
Project: Fluid-Designer   Author: Microvellum   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def format_datetime(dt, usegmt=False):
    """Turn a datetime into a date string as specified in RFC 2822.

    If usegmt is True, dt must be an aware datetime with an offset of zero.  In
    this case 'GMT' will be rendered instead of the normal +0000 required by
    RFC2822.  This is to support HTTP headers involving date stamps.
    """
    now = dt.timetuple()
    if usegmt:
        if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
            raise ValueError("usegmt option requires a UTC datetime")
        zone = 'GMT'
    elif dt.tzinfo is None:
        zone = '-0000'
    else:
        zone = dt.strftime("%z")
    return _format_timetuple_and_zone(now, zone) 
Example 14
Project: td-ameritrade-python-api   Author: areed1192   File: utils.py    License: MIT License 6 votes vote down vote up
def datetime_from_milliseconds_since_epoch(ms_since_epoch: int, timezone: datetime.timezone = None) -> datetime.datetime:
    """Converts milliseconds since epoch to a datetime object.
    
    Arguments:
    ----------
        ms_since_epoch {int} -- Number of milliseconds since epoch.
    
    Keyword Arguments:
    --------
        timezone {datetime.timezone} -- The timezone of the new datetime object. (default: {None})
    
    Returns:
    --------
        datetime.datetime -- A python datetime object.
    """

    return datetime.datetime.fromtimestamp((ms_since_epoch / 1000), tz=timezone) 
Example 15
Project: Imogen   Author: CedricGuillemet   File: utils.py    License: MIT License 6 votes vote down vote up
def format_datetime(dt, usegmt=False):
    """Turn a datetime into a date string as specified in RFC 2822.

    If usegmt is True, dt must be an aware datetime with an offset of zero.  In
    this case 'GMT' will be rendered instead of the normal +0000 required by
    RFC2822.  This is to support HTTP headers involving date stamps.
    """
    now = dt.timetuple()
    if usegmt:
        if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
            raise ValueError("usegmt option requires a UTC datetime")
        zone = 'GMT'
    elif dt.tzinfo is None:
        zone = '-0000'
    else:
        zone = dt.strftime("%z")
    return _format_timetuple_and_zone(now, zone) 
Example 16
Project: veripress   Author: veripress   File: helpers.py    License: MIT License 6 votes vote down vote up
def timezone_from_str(tz_str):
    """
    Convert a timezone string to a timezone object.

    :param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
    :return: a timezone object (tzinfo)
    """
    m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
    if m:
        # in format 'UTC±[hh]:[mm]'
        delta_h = int(m.group(1))
        delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
        return timezone(timedelta(hours=delta_h, minutes=delta_m))

    # in format 'Asia/Shanghai'
    try:
        return pytz.timezone(tz_str)
    except pytz.exceptions.UnknownTimeZoneError:
        return None 
Example 17
Project: ironpython3   Author: IronLanguages   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def format_datetime(dt, usegmt=False):
    """Turn a datetime into a date string as specified in RFC 2822.

    If usegmt is True, dt must be an aware datetime with an offset of zero.  In
    this case 'GMT' will be rendered instead of the normal +0000 required by
    RFC2822.  This is to support HTTP headers involving date stamps.
    """
    now = dt.timetuple()
    if usegmt:
        if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
            raise ValueError("usegmt option requires a UTC datetime")
        zone = 'GMT'
    elif dt.tzinfo is None:
        zone = '-0000'
    else:
        zone = dt.strftime("%z")
    return _format_timetuple_and_zone(now, zone) 
Example 18
Project: xalpha   Author: refraction-ray   File: info.py    License: MIT License 5 votes vote down vote up
def _basic_init(self):
        self._page = rget(self._url)
        if self._page.text[:800].find("Data_fundSharesPositions") >= 0:
            raise FundTypeError("This code seems to be a fund, use fundinfo instead")
        l = eval(
            re.match(
                r"[\s\S]*Data_millionCopiesIncome = ([^;]*);[\s\S]*", self._page.text
            ).groups()[0]
        )
        self.name = re.match(
            r"[\s\S]*fS_name = \"([^;]*)\";[\s\S]*", self._page.text
        ).groups()[0]
        tz_bj = dt.timezone(dt.timedelta(hours=8))
        datel = [
            dt.datetime.fromtimestamp(int(d[0]) / 1e3, tz=tz_bj).replace(tzinfo=None)
            for d in l
        ]
        ratel = [float(d[1]) for d in l]
        netvalue = [1]
        for dailyrate in ratel:
            netvalue.append(netvalue[-1] * (1 + dailyrate * 1e-4))
        netvalue.remove(1)

        df = pd.DataFrame(
            data={
                "date": datel,
                "netvalue": netvalue,
                "totvalue": netvalue,
                "comment": [0 for _ in datel],
            }
        )
        df = df[df["date"].isin(opendate)]
        if len(df) == 0:
            raise ParserFailure("no price table for %s" % self.code)
        df = df.reset_index(drop=True)
        self.price = df[df["date"] <= yesterdaydash()] 
Example 19
Project: xalpha   Author: refraction-ray   File: cons.py    License: MIT License 5 votes vote down vote up
def today_obj():
    """
    today obj in beijing timezone with no tzinfo

    :return: datetime.datetime
    """
    now = dt.datetime.now(tz=tz_bj)
    return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None)


# datetime obj for yesterdate date with time set to be 0:0:0 
Example 20
Project: glazier   Author: google   File: gtime.py    License: Apache License 2.0 5 votes vote down vote up
def now(offset: int = None) -> datetime.datetime:
  if not offset:
    offset = FLAGS.default_tz_offset
  tz = datetime.timezone(datetime.timedelta(offset))
  return datetime.datetime.now(tz) 
Example 21
Project: rets   Author: opendoor-labs   File: decoder_test.py    License: MIT License 5 votes vote down vote up
def test_decode_datetime():
    assert _decode_datetime('2017-01-02T03:04:05', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    # TODO: The standard specifies that the second fraction is limited to one
    # digit, however udatetime only permits 3 or 6 digits.
    assert _decode_datetime('2017-01-02T03:04:05.600', True) == \
           datetime(2017, 1, 2, 3, 4, 5, 600000, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05Z', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05+00:00', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05-00:00', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_datetime('2017-01-02T03:04:05+07:08', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_datetime('2017-01-02T03:04:05.600+07:08', True) == \
           datetime(2017, 1, 2, 3, 4, 5, 600000, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_datetime('2017-01-02T03:04:05-07:08', True) == \
           datetime(2017, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=-7, minutes=-8)))
    assert _decode_datetime('2017-01-02T03:04:05', False) == \
           datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T03:04:05.600', False) == \
           datetime(2017, 1, 2, 3, 4, 5, 600000)
    assert _decode_datetime('2017-01-02T03:04:05Z', False) == datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T03:04:05+00:00', False) == datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T03:04:05-00:00', False) == datetime(2017, 1, 2, 3, 4, 5)
    assert _decode_datetime('2017-01-02T12:00:00+07:08', False) == datetime(2017, 1, 2, 4, 52)
    assert _decode_datetime('2017-01-02T12:00:00-07:08', False) == datetime(2017, 1, 2, 19, 8)
    assert _decode_datetime('2017-01-01 00:00:00', False) == datetime(2017, 1, 1, 0, 0)
    assert _decode_datetime('2017-01-01', False) == datetime(2017, 1, 1, 0, 0) 
Example 22
Project: asn1tools   Author: eerimoq   File: test_codecs.py    License: MIT License 5 votes vote down vote up
def tzinfo(hours, minutes=0):
    return timezone(timedelta(hours=hours, minutes=minutes)) 
Example 23
Project: WizNote-to-OneNote   Author: CzBiX   File: onenote.py    License: Apache License 2.0 5 votes vote down vote up
def clean_html(data, doc):
    def parse_datetime(time_str):
        time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
        return time.replace(tzinfo=timezone(timedelta(hours=-8))).isoformat()

    soup = BeautifulSoup(data, 'lxml')

    pattern = re.compile(r'^index_files/(.+?)$')
    imgs = soup.find_all('img', src=pattern)

    src_file_names = []
    for img in imgs:
        src = img['src']
        match = pattern.fullmatch(src)
        file_name = match.group(1)

        src_file_names.append(file_name)
        img['src'] = 'name:' + file_name

    head_tag = soup.head
    if not head_tag:
        head_tag = soup.new_tag('head')
        soup.html.insert(0, head_tag)

    title_tag = head_tag.title
    if not title_tag:
        title_tag = soup.new_tag('title')

    # to avoid 'Untitled' in title
    title_tag.string = doc.title
    head_tag.insert(0, title_tag)

    created_tag = soup.new_tag('meta', attrs={'name': 'created', 'content': parse_datetime(doc.created)})
    head_tag.insert(1, created_tag)

    if doc.url:
        url_tag = soup.new_tag('p')
        url_tag.string = 'URL: ' + doc.url
        soup.body.insert(0, url_tag)

    return soup.encode('utf-8'), src_file_names 
Example 24
Project: git-hammer   Author: asharov   File: dbtypes.py    License: Apache License 2.0 5 votes vote down vote up
def _time_offset_to_local_time(time, offset):
    timezone = datetime.timezone(datetime.timedelta(seconds=offset))
    return time.replace(tzinfo=datetime.timezone.utc).astimezone(timezone) 
Example 25
Project: check_redfish   Author: bb-Ricardo   File: event.py    License: MIT License 5 votes vote down vote up
def get_log_entry_time(entry_date=None):

    # set to unix time 0 if no entry was passed on
    if entry_date is None:
        entry_date = "1970-01-01T00:00:00-00:00"

    # convert time zone offset from valid ISO 8601 format to python implemented datetime TZ offset
    # from:
    #   2019-11-01T15:03:32-05:00
    # to:
    #   2019-11-01T15:03:32-0500

    entry_date_object = None
    try:
        entry_date_object = datetime.datetime.strptime(entry_date[::-1].replace(":","",1)[::-1], "%Y-%m-%dT%H:%M:%S%z")
    except Exception:
        pass

    # parse time zone unaware entry dates and add this local time zone
    if entry_date_object is None:

        local_timezone = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo

        # HP event log time format
        if "T" in entry_date:
            string_format = "%Y-%m-%dT%H:%M:%SZ"
        else:
            string_format = "%Y-%m-%d %H:%M:%S"

        try:
            entry_date_object = datetime.datetime.strptime(entry_date, string_format)
            entry_date_object = entry_date_object.replace(tzinfo=local_timezone)
        except Exception:
            pass

    return entry_date_object 
Example 26
Project: Lector   Author: BasioMeusPuga   File: rarfile.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, offset, name):
            super(timezone, self).__init__()
            self._ofs, self._name = offset, name 
Example 27
Project: KubeOperator   Author: KubeOperator   File: message_client.py    License: Apache License 2.0 5 votes vote down vote up
def get_msg_content(user_message):
    content = json.loads(user_message.message.content)
    date = user_message.date_created.astimezone(timezone(timedelta(hours=8))).strftime('%Y-%m-%d %H:%M:%S')
    type = content['resource_type']
    content['detail'] = json.loads(content['detail'])
    text = ''
    if type == 'CLUSTER_EVENT':
        event_time = datetime.strptime(content['detail']['last_timestamp'],'%Y-%m-%d %H:%M:%S').astimezone(timezone(timedelta(hours=8))).strftime('%Y-%m-%d %H:%M:%S')
        text = "### " + user_message.message.title + " \n\n " + \
               "> **项目**:" + content['item_name'] + " \n\n " + \
               "> **集群**:" + content['resource_name'] + " \n\n" + \
               "> **名称**:" + content['detail']['name'] + " \n\n " + \
               "> **类别**:" + content['detail']['type'] + " \n\n " + \
               "> **原因**:" + content['detail']['reason'] + " \n\n " + \
               "> **组件**:" + content['detail']['component'] + " \n\n " + \
               "> **NameSpace**:" + content['detail']['namespace'] + " \n\n " + \
               "> **主机**:" + content['detail']['host'] + " \n\n " + \
               "> **告警时间**:" + event_time+ " \n\n " + \
               "> **详情**:" + content['detail']['message'] + " \n\n " + \
               "<font color=\"info\">本消息由KubeOperator自动发送</font>"

    if type == 'CLUSTER':
        text = "### " + user_message.message.title + "\n\n" + \
               "> **项目**:" + content['item_name'] + "\n\n" + \
               "> **集群**:" + content['resource_name'] + "\n\n" + \
               "> **信息**:" + content['detail']['message'] + "\n\n" + \
               "> **时间**:" + date + "\n\n" + \
               "<font color=\"info\">本消息由KubeOperator自动发送</font>"

    if type == 'CLUSTER_USAGE':
        text = "### " + user_message.message.title + "\n\n" + \
               "> **项目**:" + content['item_name'] + "\n\n" + \
               "> **集群**:" + content['resource_name'] + "\n\n" + \
               "> **详情**:" + content['detail']['message'] + "\n\n" + \
               "> **时间**:" + date + "\n\n" + \
               "<font color=\"info\">本消息由KubeOperator自动发送</font>"
    return text 
Example 28
Project: fastNLP   Author: fastnlp   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_now_time():
    import time
    from datetime import datetime, timezone, timedelta
    dt = datetime.utcnow()
    # print(dt)
    tzutc_8 = timezone(timedelta(hours=8))
    local_dt = dt.astimezone(tzutc_8)
    result = ("_{}_{}_{}__{}_{}_{}".format(local_dt.year, local_dt.month, local_dt.day, local_dt.hour, local_dt.minute,
                                      local_dt.second))

    return result 
Example 29
Project: imapfw   Author: OfflineIMAP   File: imaplib2.py    License: MIT License 5 votes vote down vote up
def Internaldate2Time(resp):

    """time_tuple = Internaldate2Time(resp)

    Parse an IMAP4 INTERNALDATE string.

    Return corresponding local time.  The return value is a
    time.struct_time instance or None if the string has wrong format."""

    mo = InternalDate.match(resp)
    if not mo:
        return None

    mon = Mon2num[mo.group('mon')]
    zonen = mo.group('zonen')

    day = int(mo.group('day'))
    year = int(mo.group('year'))
    hour = int(mo.group('hour'))
    min = int(mo.group('min'))
    sec = int(mo.group('sec'))
    zoneh = int(mo.group('zoneh'))
    zonem = int(mo.group('zonem'))

    # INTERNALDATE timezone must be subtracted to get UT

    zone = (zoneh*60 + zonem)*60
    if zonen == b'-':
        zone = -zone

    tt = (year, mon, day, hour, min, sec, -1, -1, -1)
    return time.localtime(calendar.timegm(tt) - zone) 
Example 30
Project: imapfw   Author: OfflineIMAP   File: imaplib2.py    License: MIT License 5 votes vote down vote up
def Time2Internaldate(date_time):

    """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time)

    Convert 'date_time' to IMAP4 INTERNALDATE representation.

    The date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time, an instance of time.struct_time (as
    returned by time.localtime()), an aware datetime instance or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format."""

    from datetime import datetime, timezone, timedelta

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, tuple):
        try:
            gmtoff = date_time.tm_gmtoff
        except AttributeError:
            if time.daylight:
                dst = date_time[8]
                if dst == -1:
                    dst = time.localtime(time.mktime(date_time))[8]
                gmtoff = -(time.timezone, time.altzone)[dst]
            else:
                gmtoff = -time.timezone
        delta = timedelta(seconds=gmtoff)
        dt = datetime(*date_time[:6], tzinfo=timezone(delta))
    elif isinstance(date_time, datetime):
        if date_time.tzinfo is None:
            raise ValueError("date_time must be aware")
        dt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    fmt = '"%d-{}-%Y %H:%M:%S %z"'.format(MonthNames[dt.month])
    return dt.strftime(fmt)