本文整理匯總了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',
)
示例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)
示例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
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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)
示例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()
示例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)
示例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)
示例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