本文整理汇总了Python中DateTime.DateTime.DateTime类的典型用法代码示例。如果您正苦于以下问题:Python DateTime类的具体用法?Python DateTime怎么用?Python DateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DateTime_to_datetime
def DateTime_to_datetime(Zope_DateTime):
"""
Convert from Zope DateTime to Python datetime and strip timezone
"""
from DateTime.DateTime import DateTime
naive = DateTime(str(Zope_DateTime).rsplit(' ', 1)[0])
return naive.asdatetime()
示例2: _convert
def _convert( self, value, default=None ):
"""Convert Date/Time value to our internal representation"""
if isinstance( value, DateTime ):
t_tup = value.parts()
elif type( value ) in (FloatType, IntType):
t_tup = time.gmtime( value )
elif type( value ) is StringType:
t_obj = DateTime( value )
t_tup = t_obj.parts()
else:
return default
yr = t_tup[0]
mo = t_tup[1]
dy = t_tup[2]
hr = t_tup[3]
mn = t_tup[4]
t_val = ( ( ( ( yr * 12 + mo ) * 31 + dy ) * 24 + hr ) * 60 + mn )
try:
# t_val must be IntType, not LongType
return int(t_val)
except OverflowError:
raise OverflowError, (
"%s is not within the range of indexable dates (index: %s)"
% (value, self.id))
示例3: tick
def tick(self):
""" Perform tick event firing when needed. """
# Check current time.
current = DateTime()
# Get lastTick. If it is invalid, set it to the minimum possible value.
last = self.getLastTick()
if not isinstance(last, DateTime):
last = DateTime(0)
else:
pass
# Get interval. Make sure the value used here is no lesser than 0.
interval = self.getInterval()
if interval < 0:
interval = 0
# If current time less lastTick is equal to or greater than
# (0.9 * interval) then set lastTick to the current time and
# execute _notify(). Otherwise do nothing.
if current.timeTime() - last.timeTime() >= 0.9 * interval:
self.setLastTick(current)
notify(TickEvent(current, self.getNextTickEstimation(
last_tick=current, interval=interval)))
示例4: getCriteriaItems
def getCriteriaItems( self ):
"""
Return a sequence of items to be used to build the catalog query.
"""
if self.value is not None:
field = self.Field()
value = self.value
operation = self.operation
# Negate the value for 'old' days
if self.daterange == 'old' and value != 0:
value = -value
# Also reverse the operator to match what a user would expect.
# Queries such as "More than 2 days ago" should match dates
# *earlier* than "today minus 2", and "Less than 2 days ago"
# would be expected to return dates *later* then "today minus
# two".
if operation == 'max':
operation = 'min'
elif operation == 'min':
operation = 'max'
date = DateTime() + value
if operation == 'within_day':
# When items within a day are requested, the range is between
# the earliest and latest time of that particular day
range = ( date.earliestTime(), date.latestTime() )
return ( ( field, {'query': range, 'range': 'min:max'} ), )
elif operation == 'min':
if value != 0:
if self.daterange == 'old':
date_range = (date, DateTime())
return ( ( field, { 'query': date_range
, 'range': 'min:max'
} ), )
else:
return ( ( field, { 'query': date.earliestTime()
, 'range': operation
} ), )
else:
# Value 0 means "Now", so get everything from now on
return ( ( field, {'query': date,'range': operation } ), )
elif operation == 'max':
if value != 0:
if self.daterange == 'old':
return ((field, {'query': date, 'range': operation}),)
else:
date_range = (DateTime(), date.latestTime())
return ( ( field, { 'query': date_range
, 'range': 'min:max'
} ), )
else:
# Value is 0, meaning "Now", get everything before "Now"
return ( ( field, {'query': date, 'range': operation} ), )
else:
return ()
示例5: test_timezone_metadata
def test_timezone_metadata(self):
# http://www.zope.org/Collectors/CMF/325
# If an item's timestamp(s) are stored in another timezone,
# e.g. 4 hours further away from UTC, the DC date methods
# should still return it in the local timezone so that all
# user-visible dates can be compared to each other by eye.
site = DummySite('site').__of__(self.root)
item = self._makeDummyContent('item').__of__(site)
dates_and_methods = (
('modification_date', 'ModificationDate'),
('effective_date', 'EffectiveDate'),
('effective_date', 'Date'),
('expiration_date', 'ExpirationDate'),
('creation_date', 'CreationDate'))
offset = 4 # arbitrary, any value should work.
for datename, dc_methodname in dates_and_methods:
orig = getattr(item, datename)
# Some default to None, fix that.
if orig is None:
orig = DateTime()
setattr(item, datename, orig)
orig_DC = getattr(item, dc_methodname)()
# Change the timezone of the date.
local_offset = orig.tzoffset() % (3600*24)
other_offset = (local_offset + offset) % 24
otherzone = 'GMT+%d' % other_offset
setattr(item, datename, orig.toZone(otherzone))
# Finally, verify that display has not changed.
new_DC = getattr(item, dc_methodname)()
self.assertEqual(orig_DC, new_DC)
示例6: _convert
def _convert(self, value, default=None):
"""Convert Date/Time value to our internal representation"""
if isinstance(value, DateTime):
t_tup = value.toZone('UTC').parts()
elif isinstance(value, (float, int)):
t_tup = time.gmtime(value)
elif isinstance(value, str) and value:
t_obj = DateTime(value).toZone('UTC')
t_tup = t_obj.parts()
elif isinstance(value, datetime):
if self.index_naive_time_as_local and value.tzinfo is None:
value = value.replace(tzinfo=Local)
# else if tzinfo is None, naive time interpreted as UTC
t_tup = value.utctimetuple()
elif isinstance(value, date):
t_tup = value.timetuple()
else:
return default
yr = t_tup[0]
mo = t_tup[1]
dy = t_tup[2]
hr = t_tup[3]
mn = t_tup[4]
t_val = ((((yr * 12 + mo) * 31 + dy) * 24 + hr) * 60 + mn)
if t_val > MAX32:
# t_val must be integer fitting in the 32bit range
raise OverflowError(
"%s is not within the range of indexable dates (index: %s)"
% (value, self.id))
return t_val
示例7: getMonthAndYear
def getMonthAndYear(self):
""" Retrieve month/year tuple
"""
caltool = getUtility(ICalendarTool)
current = DateTime()
session = None
# First priority goes to the data in the request
year = self.request.get('year', None)
month = self.request.get('month', None)
# Next get the data from the SESSION
if caltool.getUseSession():
session = self.request.get('SESSION', None)
if session:
if not year:
year = session.get('calendar_year', None)
if not month:
month = session.get('calendar_month', None)
# Last resort to today
if not year:
year = current.year()
if not month:
month = current.month()
# Then store the results in the session for next time
if session:
session.set('calendar_year', year)
session.set('calendar_month', month)
# Finally return the results
return (year, month)
示例8: _FSCacheHeaders
def _FSCacheHeaders(obj):
# Old-style setting of modified headers for FS-based objects
REQUEST = getattr(obj, 'REQUEST', None)
if REQUEST is None:
return False
RESPONSE = REQUEST.RESPONSE
header = REQUEST.get_header('If-Modified-Since', None)
last_mod = obj._file_mod_time
if header is not None:
header = header.split(';')[0]
# Some proxies seem to send invalid date strings for this
# header. If the date string is not valid, we ignore it
# rather than raise an error to be generally consistent
# with common servers such as Apache (which can usually
# understand the screwy date string as a lucky side effect
# of the way they parse it).
try:
mod_since=DateTime(header)
mod_since=long(mod_since.timeTime())
except TypeError:
mod_since=None
if mod_since is not None:
if last_mod > 0 and last_mod <= mod_since:
RESPONSE.setStatus(304)
return True
#Last-Modified will get stomped on by a cache policy if there is
#one set....
RESPONSE.setHeader('Last-Modified', rfc1123_date(last_mod))
示例9: _convertDateTime
def _convertDateTime( self, value ):
if value is None:
return value
if type( value ) == type( '' ):
dt_obj = DateTime( value )
value = dt_obj.millis() / 1000 / 60 # flatten to minutes
if isinstance( value, DateTime ):
value = value.millis() / 1000 / 60 # flatten to minutes
return int( value )
示例10: report
def report(self, current, *args, **kw):
if current > 0:
if current % self._steps == 0:
seconds_so_far = time.time() - self._start
seconds_to_go = (seconds_so_far / current *
(self._max - current))
end = DateTime(time.time() + seconds_to_go)
self.output('%d/%d (%.2f%%) Estimated termination: %s' % \
(current, self._max, (100.0 * current / self._max),
end.strftime('%Y/%m/%d %H:%M:%Sh')))
示例11: testValidationRequiredSplitDate
def testValidationRequiredSplitDate(self):
s1 = getattr(self, 's1')
sdq1 = getattr(s1, 'sdq1')
sdq1.setRequired(True)
now = DateTime()
now_value = str(now.year()) + '/' + str(now.month()) + '/' + str(now.day()) + ' ' + str(now.hour()) + ':' + str(now.minute()) + ':00 GMT'
self.layer['request'].form['sdq1_ampm'] = ''
self.layer['request'].form['sdq1_day'] = str(now.day())
self.layer['request'].form['sdq1_hour'] = str(now.hour())
self.layer['request'].form['sdq1_minute'] = str(now.minute())
self.layer['request'].form['sdq1_month'] = str(now.month())
self.layer['request'].form['sdq1_year'] = str(now.year())
dummy_controller_state = ControllerState(
id='survey_view',
context=s1,
button='submit',
status='success',
errors={},
next_action=None,)
controller = self.portal.portal_form_controller
controller_state = controller.validate(dummy_controller_state, self.layer['request'], ['validate_survey',])
assert controller_state.getErrors() == {}, "Validation error raised: %s" % controller_state.getErrors()
userid = s1.getSurveyId()
assert userid == "test_user_1_", "Not default test user"
questions = s1.getQuestions()
for question in questions:
if question.portal_type == 'Survey Date Question':
assert question.getAnswerFor(userid) == now_value, "Answer not saved correctly: %s" % question.getAnswerFor(userid)
示例12: getUpdateBase
def getUpdateBase(self, obj=None):
"""
Return the base date formatted as RFC 822 to be used with the update
frequency and the update period to calculate a publishing schedule.
"""
if obj is not None:
base = self.getSyndicationInfo(obj).base
else:
base = self.base
as_zope = DateTime(base.isoformat())
return as_zope.rfc822()
示例13: test_Today
def test_Today(self):
friendly = self._makeOne("foo", "foofield")
friendly.apply(self.today)
self.assertEqual(friendly.daterange, "ahead")
now = DateTime()
result = friendly.getCriteriaItems()
self.assertEqual(len(result), 1)
self.assertEqual(result[0][0], "foofield")
self.assertEqual(result[0][1]["query"], (now.earliestTime(), now.latestTime()))
self.assertEqual(result[0][1]["range"], "min:max")
示例14: _convertDateTime
def _convertDateTime( self, value ):
if value is None:
return value
if type( value ) == type( '' ):
dt_obj = DateTime( value )
value = dt_obj.millis() / 1000 / 60 # flatten to minutes
if isinstance( value, DateTime ):
value = value.millis() / 1000 / 60 # flatten to minutes
result = int( value )
if isinstance(result, long): # this won't work (Python 2.3)
raise OverflowError( '%s is not within the range of dates allowed'
'by a DateRangeIndex' % value)
return result
示例15: test_Today
def test_Today( self ):
friendly = self._makeOne('foo', 'foofield')
friendly.apply( self.today )
self.assertEqual( friendly.daterange, 'ahead' )
now = DateTime()
result = friendly.getCriteriaItems()
self.assertEqual( len(result), 1 )
self.assertEqual( result[0][0], 'foofield' )
self.assertEqual( result[0][1]['query'],
( now.earliestTime(), now.latestTime() ) )
self.assertEqual( result[0][1]['range'], 'min:max' )