def testTzAll(self):
from dateutil.tz import tzutc
from dateutil.tz import tzoffset
from dateutil.tz import tzlocal
from dateutil.tz import tzfile
from dateutil.tz import tzrange
from dateutil.tz import tzstr
from dateutil.tz import tzical
from dateutil.tz import gettz
from dateutil.tz import tzwin
from dateutil.tz import tzwinlocal
tz_all = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange",
"tzstr", "tzical", "gettz"]
tz_all += ["tzwin", "tzwinlocal"] if sys.platform.startswith("win") else []
lvars = locals()
for var in tz_all:
self.assertIsNot(lvars[var], None)
python类tzoffset()的实例源码
def test_pass_naive_timestamp_default_timezone(self):
"""
The incoming value is a naive timestamp, but the Filter is
configured not to treat naive timestamps as UTC.
"""
self.assertFilterPasses(
self._filter(
'2015-05-12 03:20:03',
# The Filter is configured to parse naive timestamps as
# if they are UTC+8.
timezone = tzoffset('UTC+8', 8*3600)
),
# The resulting date appears to occur 1 day earlier because
# the Filter subtracted 8 hours to convert the value to
# UTC.
date(2015, 5, 11),
)
def test_pass_aware_timestamp_default_timezone(self):
"""
The Filter's default timezone has no effect if the incoming
value already contains timezone info.
"""
self.assertFilterPasses(
# The incoming timestamp is from UTC+4, but the Filter is
# configured to use UTC-11 by default.
self._filter(
'2015-05-11T03:14:38+04:00',
timezone = tzoffset('UTC-11', -11*3600)
),
# Because the incoming timestamp has timezone info, the
# Filter uses that instead of the default value.
# Note that the this test will fail if the Filter uses the
# UTC-11 timezone (the result will be 1 day ahead).
date(2015, 5, 10),
)
def test_pass_naive_timestamp_default_timezone(self):
"""
The incoming value is a naive timestamp, but the Filter is
configured not to treat naive timestamps as UTC.
"""
self.assertFilterPasses(
# The incoming value is a naive timestamp, and the Filter
# is configured to use UTC+8 by default.
self._filter(
'2015-05-12 09:20:03',
timezone = tzoffset('UTC+8', 8*3600),
),
# The resulting datetime is still converted to UTC.
datetime(2015, 5, 12, 1, 20, 3, tzinfo=utc),
)
def test_return_naive_datetime(self):
"""
You can configure the filter to return a naive datetime object
(e.g., for storing in a database).
Note that the datetime is still converted to UTC before its
tzinfo is removed.
"""
self.assertFilterPasses(
self._filter(
datetime(
2015, 7, 1, 9, 22, 10,
tzinfo=tzoffset('UTC-5', -5*3600),
),
# Note that we pass `naive=True` to the Filter's
# initializer.
naive = True,
),
# The resulting datetime is converted to UTC before its
# timezone info is stripped.
datetime(2015, 7, 1, 14, 22, 10, tzinfo=None),
)
def now():
"""
Get the current datetime.
:return: The current datetime.
"""
return datetime.utcnow().replace(tzinfo=tzoffset(None, 0))
# Class Methods
# Public Methods
# Protected Methods
# Private Methods
# Properties
# Representation and Comparison
def normalize_date(date):
try:
# See if date is a `time.struct_time`
# if so, convert it and account for leapseconds
tt, date = date, dt(*date[:5] + (min(date[5], 59),))
except TypeError:
pass
else:
is_dst = None if tt[8] is -1 else tt[8]
try:
tm_zone = tt.tm_zone
except AttributeError:
tm_zone = None
tm_gmtoff = None
else:
tm_gmtoff = tt.tm_gmtoff
if tm_zone:
date = pytz.timezone(tm_zone).localize(date, is_dst=is_dst)
elif tm_gmtoff:
offset = tzoffset(None, tm_gmtoff)
date.replace(tzinfo=offset)
# Set timezone to UTC
try:
tzdate = date.astimezone(utc) if date.tzinfo else utc.localize(date)
except AttributeError:
tzdate = date
return tzdate
def setUp(self):
self.tzinfos = {"BRST": -10800}
self.brsttz = tzoffset("BRST", -10800)
self.default = datetime(2003, 9, 25)
# Parser should be able to handle bytestring and unicode
base_str = '2014-05-01 08:00:00'
try:
# Python 2.x
self.uni_str = unicode(base_str)
self.str_str = str(base_str)
except NameError:
self.uni_str = str(base_str)
self.str_str = bytes(base_str.encode())
def testInequality(self):
UTC = tz.tzutc()
UTCp4 = tz.tzoffset('UTC+4', 14400)
self.assertNotEqual(UTC, UTCp4)
def testTimedeltaOffset(self):
est = tz.tzoffset('EST', timedelta(hours=-5))
est_s = tz.tzoffset('EST', -18000)
self.assertEqual(est, est_s)
def testTzNameNone(self):
gmt5 = tz.tzoffset(None, -18000) # -5:00
self.assertIs(datetime(2003, 10, 26, 0, 0, tzinfo=gmt5).tzname(),
None)
def testTzOffsetRepr(self):
tname = 'EST'
tzo = tz.tzoffset(tname, -5 * 3600)
self.assertEqual(repr(tzo), "tzoffset(" + repr(tname) + ", -18000)")
def testEquality(self):
utc = tz.tzoffset('UTC', 0)
gmt = tz.tzoffset('GMT', 0)
self.assertEqual(utc, gmt)
def testUTCEquality(self):
utc = tz.tzutc()
o_utc = tz.tzoffset('UTC', 0)
self.assertEqual(utc, o_utc)
self.assertEqual(o_utc, utc)
def testInequalityInvalid(self):
tzo = tz.tzoffset('-3', -3 * 3600)
self.assertFalse(tzo == -3)
self.assertNotEqual(tzo, -3)
def testInequalityUnsupported(self):
tzo = tz.tzoffset('-5', -5 * 3600)
self.assertTrue(tzo == ComparesEqual)
self.assertFalse(tzo != ComparesEqual)
self.assertEqual(tzo, ComparesEqual)
def testInequalityFixedOffset(self):
tzl = tz.tzlocal()
tzos = tz.tzoffset('LST', total_seconds(tzl._std_offset))
tzod = tz.tzoffset('LDT', total_seconds(tzl._std_offset))
self.assertFalse(tzl == tzos)
self.assertFalse(tzl == tzod)
self.assertTrue(tzl != tzos)
self.assertTrue(tzl != tzod)
def testPickleTzOffsetZero(self):
self.assertPicklable(tz.tzoffset('UTC', 0))
def testPickleTzOffsetPos(self):
self.assertPicklable(tz.tzoffset('UTC+1', 3600))
def testPickleTzOffsetNeg(self):
self.assertPicklable(tz.tzoffset('UTC-1', -3600))
def test_pass_alternate_timezone_syntax(self):
"""
When setting the default timezone for the Filter, you can use
an int/float offset (number of hours from UTC) instead of a
tzoffset object.
"""
self.assertFilterPasses(
# Note that we use an int value instead of constructing a
# tzoffset for `timezone`.
self._filter('2015-05-11 21:14:38', timezone=-8),
date(2015, 5, 12),
)
def test_pass_datetime_non_utc(self):
"""
The incoming value is a datetime object with a non-UTC
timezone.
"""
self.assertFilterPasses(
datetime(
2015, 6, 27, 22, 6, 32,
tzinfo=tzoffset('UTC-5', -5*3600),
),
# As you probably already guessed, the datetime gets
# converted to UTC before it is converted to a date.
date(2015, 6, 28),
)
def test_pass_alternate_timezone_syntax(self):
"""
When setting the default timezone for the Filter, you can use
an int/float offset (number of hours from UTC) instead of a
tzoffset object.
"""
self.assertFilterPasses(
# Note that we use an int value instead of constructing a
# tzoffset for ``timezone``.
self._filter('2015-05-11 21:14:38', timezone=3),
datetime(2015, 5, 11, 18, 14, 38, tzinfo=utc),
)
def test_pass_datetime_non_utc(self):
"""
The incoming value is a datetime object that is already set to
a non-UTC timezone.
"""
self.assertFilterPasses(
datetime(2015, 6, 27, 10, 6, 32, tzinfo=tzoffset('UTC-5',-5*3600)),
datetime(2015, 6, 27, 15, 6, 32, tzinfo=utc),
)
def __init__(self, timezone=None, naive=False):
# type: (Optional[Union[tzinfo, int, float]], bool) -> None
"""
:param timezone:
Specifies the timezone to use when the *incoming* value is
a naive timestamp. Has no effect on timezone-aware
timestamps.
IMPORTANT: The result is always converted to UTC,
regardless of the value of the ``timezone`` param!
You can provide an int/float here, which is the offset from
UTC in hours (e.g., 5 = UTC+5).
:param naive:
If True, the filter will *return* naive datetime objects
(sans tzinfo). This is useful e.g., for datetimes that
will be stored in a database that doesn't understand aware
timestamps.
IMPORTANT: Incoming values are still converted to UTC
before stripping tzinfo!
"""
super(Datetime, self).__init__()
if not isinstance(timezone, tzinfo):
if timezone in [0, None]:
timezone = utc
else:
# Assume that we got an int/float instead.
timezone = tzoffset(
name = 'UTC{offset:+}'.format(offset=timezone),
offset = float(timezone) * 3600.0,
)
self.timezone = timezone
self.naive = naive
def parse(cls, string):
tzinfo = None
if string == 'local':
tzinfo = tz.tzlocal()
elif string in ['utc', 'UTC']:
tzinfo = tz.tzutc()
else:
iso_match = cls._TZINFO_RE.match(string)
if iso_match:
sign, hours, minutes = iso_match.groups()
seconds = int(hours) * 3600 + int(minutes) * 60
if sign == '-':
seconds *= -1
tzinfo = tz.tzoffset(None, seconds)
else:
tzinfo = tz.gettz(string)
if tzinfo is None:
raise ParserError('Could not parse timezone expression "{0}"', string)
return tzinfo
def whenareyou_apt(airport):
if not airports_dict[airport]['tz_olson']=='\\N':
return timezone(airports_dict[airport]['tz_olson'])
else:
tzinfo = get_tz(float(airports_dict[airport]['lat']),
float(airports_dict[airport]['lng']))
if tzinfo:
return tzinfo
else:
tot_offset = float(airports_dict[airport]['tz'])*3600
return tz.tzoffset(airports_dict[airport]['name'] + ' ' +
airports_dict[airport]['city'], tot_offset)
def test_parse_iso8601():
"""Test parsing ISO-8601 date/time strings."""
as_string = "2016-02-05T02:52:15.030474+01:00"
as_datetime = datetime(2016, 2, 5, 2, 52, 15, 30474, tzinfo=tzoffset(None, 3600))
assert parse_iso8601(as_string) == as_datetime
as_string = "2016-02-05T02:52:15"
as_datetime = datetime(2016, 2, 5, 2, 52, 15, tzinfo=timezone.utc)
assert parse_iso8601(as_string) == as_datetime
with pytest.raises(ValueError) as e:
parse_iso8601("foobar")
assert "Unknown string format" in str(e.value)
test_timezones.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def test_timestamp_to_datetime_tzoffset(self):
# tzoffset
from dateutil.tz import tzoffset
tzinfo = tzoffset(None, 7200)
expected = Timestamp('3/11/2012 04:00', tz=tzinfo)
result = Timestamp(expected.to_datetime())
self.assertEqual(expected, result)
test_timezones.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def test_dateutil_tzoffset_support(self):
from dateutil.tz import tzoffset
values = [188.5, 328.25]
tzinfo = tzoffset(None, 7200)
index = [datetime(2012, 5, 11, 11, tzinfo=tzinfo),
datetime(2012, 5, 11, 12, tzinfo=tzinfo)]
series = Series(data=values, index=index)
self.assertEqual(series.index.tz, tzinfo)
# it works! #2443
repr(series.index[0])