當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.timezone方法代碼示例

本文整理匯總了Python中datetime.timezone方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.timezone方法的具體用法?Python datetime.timezone怎麽用?Python datetime.timezone使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime的用法示例。


在下文中一共展示了datetime.timezone方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_invalid_tz_offsets_too_large

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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',
        ) 
開發者ID:closeio,項目名稱:ciso8601,代碼行數:19,代碼來源:tests.py

示例2: test_decode_time

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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) 
開發者ID:opendoor-labs,項目名稱:rets,代碼行數:21,代碼來源:decoder_test.py

示例3: upload_backup_file

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:KubeOperator,項目名稱:KubeOperator,代碼行數:18,代碼來源:cluster_backup_utils.py

示例4: parse_timezone

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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) 
開發者ID:pypa,項目名稱:pipenv,代碼行數:22,代碼來源:iso8601.py

示例5: __init__

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:pvlib,項目名稱:pvlib-python,代碼行數:26,代碼來源:location.py

示例6: test_attributes

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:RhetTbull,項目名稱:osxphotos,代碼行數:24,代碼來源:test_mojave_10_14_5.py

示例7: test_attributes

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:RhetTbull,項目名稱:osxphotos,代碼行數:24,代碼來源:test_catalina_10_15_1.py

示例8: test_attributes

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:RhetTbull,項目名稱:osxphotos,代碼行數:24,代碼來源:test_10_12_6.py

示例9: test_attributes

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:RhetTbull,項目名稱:osxphotos,代碼行數:26,代碼來源:test_mojave_10_14_6.py

示例10: test_attributes

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:RhetTbull,項目名稱:osxphotos,代碼行數:24,代碼來源:test_catalina_10_15_4.py

示例11: retro_add

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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) 
開發者ID:Ambro17,項目名稱:AmbroBot,代碼行數:20,代碼來源:commands.py

示例12: incremented_count

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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() 
開發者ID:JeNeSuisPasDave,項目名稱:authenticator,代碼行數:22,代碼來源:data.py

示例13: format_datetime

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:19,代碼來源:utils.py

示例14: datetime_from_milliseconds_since_epoch

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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) 
開發者ID:areed1192,項目名稱:td-ameritrade-python-api,代碼行數:19,代碼來源:utils.py

示例15: timezone_from_str

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timezone [as 別名]
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 
開發者ID:veripress,項目名稱:veripress,代碼行數:21,代碼來源:helpers.py


注:本文中的datetime.timezone方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。