예제 #1
0
	def workout_list(self, max_results=40, before=None):
		""" Retrieve workouts.

		:param before: datetime object or iso format date string (%Y-%m-%d %H:%M:%S UTC)
		:param max_results: Maximum number of workouts to be returned.
		"""

		params = {
			'maxResults': max_results
		}

		if before != None:
			if type(before) is datetime:
				## Endomondo _really_ needs timezone
				if before.tzinfo != None:
					before = before.astimezone(tzinfo('UTC'))

				params['before'] = before.strftime('%Y-%m-%d %H:%M:%S UTC')
			elif type(before) is str:
				params['before'] = before
			else:
				raise ValueError("param 'before needs to be datetime object or iso formatted string.")

		r = self.make_request(self.URL_WORKOUTS, params)

		workouts = []
		for entry in r.json()['data']:
			workout = Workout(entry)
			workouts.append(workout)

		return workouts
예제 #2
0
파일: cpt.py 프로젝트: manasij7479/cling
def box_draw_header():
    msg='cling (' + platform.machine() + ')' + formatdate(time.time(),tzinfo())
    spaces_no = 80 - len(msg) - 4
    spacer = ' ' * spaces_no
    msg='cling (' + platform.machine() + ')' + spacer + formatdate(time.time(),tzinfo())

    if OS != 'Windows':
        print '''
╔══════════════════════════════════════════════════════════════════════════════╗
║ %s ║
╚══════════════════════════════════════════════════════════════════════════════╝'''%(msg)
    else:
        print '''
+=============================================================================+
| %s|
+=============================================================================+'''%(msg)
예제 #3
0
    def test_dst_when_not_dst(self):
        dt = datetime(2012, 1, 1, tzinfo=tzinfo())
        offset = timedelta(hours=0)

        result = CETTimeZone().dst(dt)

        self.assertEqual(result, offset)
예제 #4
0
 def test_interfaces(self):
     verifyObject(ITimeDelta, timedelta(minutes=20))
     verifyObject(IDate, date(2000, 1, 2))
     verifyObject(IDateTime, datetime(2000, 1, 2, 10, 20))
     verifyObject(ITime, time(20, 30, 15, 1234))
     verifyObject(ITZInfo, tzinfo())
     verifyClass(ITimeDeltaClass, timedelta)
     verifyClass(IDateClass, date)
     verifyClass(IDateTimeClass, datetime)
     verifyClass(ITimeClass, time)
예제 #5
0
    def test_obs_time_string_success(self):
        from snowlert.lib import noaa

        test_data = 'Last Updated on Jul 5 2014, 4:55 pm PDT'

        expected = datetime(year=2014, month=7, day=5, hour=16, minute=55, tzinfo=tzinfo('PDT')).isoformat()

        actual = noaa._parse_observation_time_string(test_data)

        self.assertEqual(expected, actual)
예제 #6
0
 def __init__(self, timezone='UTC'):
       self.created=""
       self.UID=""
       self.summary=""
       self.completed=""
       self.location = ""
       self.due=""
       self.sched = ""
       self.description=""
       self.tz = tzinfo(timezone)
       return
예제 #7
0
def datetime_to_str(date):
	''' Convert datetime object into string presentation
		TODO: Convert local timezone to UTC.
	'''
	if type(date) == str:
		return date

	if date.tzinfo != None:
		date = date.astimezone(tzinfo('UTC'))
	text = date.strftime('%Y-%m-%d %H:%M:%S UTC')
	return text
예제 #8
0
	def workout_list(self, max_results=40, before=None):
		""" Retrieve workouts.

		:param before: datetime object or iso format date string (%Y-%m-%d %H:%M:%S UTC)
		:param max_results: Maximum number of workouts to be returned.
		"""

		params = {
			'maxResults': max_results
		}

		if before != None:
			if type(before) is datetime:
				## Endomondo _really_ needs timezone
				if before.tzinfo != None:
					before = before.astimezone(tzinfo('UTC'))

				params['before'] = before.strftime('%Y-%m-%d %H:%M:%S UTC')
			elif type(before) is str:
				params['before'] = before
			else:
				raise ValueError("param 'before needs to be datetime object or iso formatted string.")

		r = self.make_request(self.URL_WORKOUTS, params)

		workouts = []
		for entry in r.json()['data']:
			workout = EndomondoWorkout(self)

			workout.id = entry['id']

			if entry.has_key('name'):
				workout.summary = entry['name']
			elif self.sports_map.has_key(entry['sport']):
				workout.summary = self.sports_map[entry['sport']]
			else:
				print self.sports_map
				print "Sports entry: %s" % entry['sport']
				workout.summary = 'Sports'

			workout.start_time = self._parse_date(entry['start_time'])
			workout.end_time   = workout.start_time + timedelta(seconds=entry['duration_sec'])

			if entry.has_key('note'):
				workout.note = entry['note']

			if entry['has_points'] == True:
				self._location = False

			workouts.append(workout)

		return workouts
예제 #9
0
 def test_tz_without_normalize(self):
     tz = tzinfo()
     self.assertFalse(hasattr(tz, 'normalize'))
     self.assertTrue(localize(make_aware(datetime.utcnow(), tz), tz))
예제 #10
0
# built-in constants (CH 4)
a["CopyrightType"] = copyright
# built-in types (CH 5)
a["ClassObjectType"] = _newclass  # <type 'type'>
a["ClassInstanceType"] = _newclass()  # <type 'class'>
a["SetType"] = _set = set()
a["FrozenSetType"] = frozenset()
# built-in exceptions (CH 6)
a["ExceptionType"] = _exception = _function2()[0]
# string services (CH 7)
a["SREPatternType"] = _srepattern = re.compile("")
# data types (CH 8)
a["ArrayType"] = array.array("f")
a["DequeType"] = collections.deque([0])
a["DefaultDictType"] = collections.defaultdict(_function, _dict)
a["TZInfoType"] = datetime.tzinfo()
a["DateTimeType"] = datetime.datetime.today()
a["CalendarType"] = calendar.Calendar()
if not PY3:
    a["SetsType"] = sets.Set()
    a["ImmutableSetType"] = sets.ImmutableSet()
    a["MutexType"] = mutex.mutex()
# numeric and mathematical types (CH 9)
a["DecimalType"] = decimal.Decimal(1)
a["CountType"] = itertools.count(0)
# data compression and archiving (CH 12)
a["TarInfoType"] = tarfile.TarInfo()
# generic operating system services (CH 15)
a["LoggerType"] = logging.getLogger()
a["FormatterType"] = logging.Formatter()  # pickle ok
a["FilterType"] = logging.Filter()  # pickle ok
예제 #11
0
import pytz
import pytz.tzfile


class tzabbr(datetime.tzinfo):
    """A timezone abbreviation.

  *WARNING*: This is not a tzinfo implementation! Trying to use this as tzinfo
  object will result in failure.  We inherit from datetime.tzinfo so we can get
  through the dateutil checks.
  """
    pass


# A "marker" tzinfo object which is used to signify an unknown timezone.
unknown = datetime.tzinfo(0)

regions = {'all': {}, 'military': {}}
# Create a special alias for the all and military regions
all = regions['all']
military = regions['military']


def tzabbr_register(abbr, name, region, zone, dst):
    """Register a new timezone abbreviation in the global registry.

  If another abbreviation with the same name has already been registered it new
  abbreviation will only be registered in region specific dictionary.
  """
    newabbr = tzabbr()
    newabbr.abbr = abbr
예제 #12
0
def test_convert_datetime_type_with_tz():
    # This ensures datetimes are sent to BokehJS timezone-naive
    # see https://github.com/bokeh/bokeh/issues/6480
    for tz in pytz.all_timezones:
        assert bus.convert_datetime_type(datetime.datetime(2016, 5, 11, tzinfo=datetime.tzinfo(tz))) == 1462924800000.0
예제 #13
0
    'Shinen': ['HatredPerson'],
    'phenjan': ['Scuns87'],
    'Итианаа': ['tahena'],
    'ОплотМнеВРот': ['Soarelia', 'PlotArmor'],
    'Cerethrius': ['Soarelia', 'PlotArmor', 'Renbrane'],
    'Phantasm': ['ElderSign'],
    'Farfelkygelain': ['Farfelkygelain'],
    'Maeve': ['notaloneindec'],
    'Shiawase': ['ProoFFie'],
    'Сахарок': ['Soarelia', 'PlotArmor'],
    'cat Leopold': ['Soarelia', 'Scuns87'],
    'Kronprincen': ['Soarelia', 'PlotArmor', 'Renbrane']
}

guild_keys = guild_dict.keys()
tz = datetime.tzinfo('Europe/Moscow')
tz = datetime.timezone(datetime.timedelta(hours=3))

f_evening = datetime.datetime(1, 1, 1, 16, 45, 0, 0, tz)
f_morning = datetime.datetime(1, 1, 1, 8, 45, 0, 0, tz)
f_night = datetime.datetime(1, 1, 1, 00, 45, 0, 0, tz)

const_times_f = [f_morning, f_evening, f_night]


def righttime(message):
    now = datetime.datetime.fromtimestamp(message.date, tz)
    for time_f in const_times_f:
        if ((time_f.hour - now.hour == 0) and (now.minute - time_f.minute > 0)
                and (time_f.minute - now.minute <= 14)):
            list_for_ping = create_list_for_ping(message.text)
예제 #14
0
 def test_no_tzinfo(self):
     """no_tzinfo should have known output"""
     dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.tzinfo('MST'))
     self.assertEqual(dt.replace(tzinfo=None), t.no_tzinfo(dt))
     ans = [datetime.datetime(2000, 1, 1)] * 10
     self.assertEqual(ans, t.no_tzinfo([dt] * 10))
예제 #15
0
def test_convert_datetime_type_with_tz():
    # This ensures datetimes are sent to BokehJS timezone-naive
    # see https://github.com/bokeh/bokeh/issues/6480
    for tz in pytz.all_timezones:
        assert bus.convert_datetime_type(datetime.datetime(2016, 5, 11, tzinfo=datetime.tzinfo(tz))) == 1462924800000.0
def test_datetime_with_tz_not_a_string():
    assert DateTime(tz=datetime.tzinfo())
예제 #17
0
import eeml
import serial
import datetime

a = datetime.tzinfo()

# parameters
API_KEY = 'YOUR_API_KEY'
# API_URL = '/v2/feeds/42166.xml'
API_URL = 42166

readings = [3, 4]
pac = eeml.Cosm(API_URL, API_KEY)
at = datetime.datetime(2012, 9, 12, 11, 0, 0)

pac.update([
        eeml.Data("Temperature", readings[0], unit=eeml.Celsius(), at=at), 
        eeml.Data("Humidity", readings[1], unit=eeml.RH())])
pac.put()
print pac.geteeml()
예제 #18
0
def expire(second=None, minute=None, hour=None, day=None, day_of_week=None, week=None, month=None, tz=None, maxsize=128, persistent='', custom=None, **kwargs):
    '''Expires all entries in the cache @ whole number time

        for example, @expire(0, 30, 16) will expire the cache at 4:30pm every day
    '''
    if not any((second is not None, minute is not None, hour is not None, day is not None, week is not None, month is not None)):
        second = 0

    if second is not None and second >= 60:
        raise TCException('second must be < 60')

    if minute is not None and minute >= 60:
        raise TCException('minute must be < 60')

    if hour is not None and hour >= 24:
        raise TCException('minute must be < 24')

    if day is not None and (day <= 0 or day > 31):
        raise TCException('day must be > 0, < 32')
    # elif day is not None:
    #     day += 1  # for convenience

    if day_of_week is not None and (day_of_week <= 0 or day > 8):
        raise TCException('day_of_weel must be > 0, < 8')

    if week is not None and (week <= 0 or week > 5):
        raise TCException('day must be > 0, < 6')
    # elif week is not None:
    #     week += 1  # for convenience

    if month is not None and (month <= 0 or month > 12):
        raise TCException('month must be >0, < 13')
    # elif month is not None:
    #     month += 1  # for convenience

    try:
        tz = tz or get_localzone()
    except AttributeError:
        tz = time.tzname[time.daylight]

    if isinstance(tz, str):
        try:
            tz = pytz.timezone(tz)
        except pytz.UnknownTimeZoneError:
            tz = datetime.tzinfo(tz)

    def _wrapper(foo):
        last = datetime.datetime.now(tz=tz)

        if custom:
            foo = custom(**kwargs)(foo)
        elif persistent:
            foo = persistent_lru_cache(persistent, maxsize=maxsize)(foo)
        else:
            foo = lru_cache(maxsize)(foo)

        @wraps(foo)
        def _wrapped_foo(*args, **kwargs):
            nonlocal last

            now = datetime.datetime.now(tz=tz)
            if should_expire(last, now, second, minute, hour, day, day_of_week, week, month):
                foo.cache_clear()
            last = now

            args = tuple([frozendict(arg) if isinstance(arg, dict) else tuple(arg) if isinstance(arg, list) else arg for arg in args])
            kwargs = {k: frozendict(v) if isinstance(v, dict) else tuple(v) if isinstance(v, list) else v for k, v in kwargs.items()}

            return foo(*args, **kwargs)
        return _wrapped_foo
    return _wrapper
예제 #19
0
    (timedelta_safe(1), "timedelta_safe(1)"),
    (timedelta_safe(1, 2), "timedelta_safe(1, 2)"),
    (timedelta_safe(1, 2, 3), "timedelta_safe(1, 2, 3)"),
])
def test_repr(obj, expected):
    # XXX: there's a discrepancy between datetime.py and CPython's _datetime
    # for the repr() of Python-defined subclasses of datetime classes.
    assert repr(obj).endswith(expected)


@pytest.mark.parametrize("obj", [
    datetime.date.today(),
    datetime.time(),
    datetime.datetime.utcnow(),
    datetime.timedelta(),
    datetime.tzinfo(),
])
def test_attributes(obj):
    with pytest.raises(AttributeError):
        obj.abc = 1


def test_timedelta_init_long():
    td = datetime.timedelta(microseconds=20000000000000000000)
    assert td.days == 231481481
    assert td.seconds == 41600
    td = datetime.timedelta(microseconds=20000000000000000000.)
    assert td.days == 231481481
    assert td.seconds == 41600

예제 #20
0
    td.replace(year=2030, month=12),
    datetime.time(hour=23, minute=59, second=59, microsecond=999999),
    datetime.datetime(year=9999,
                      month=12,
                      day=31,
                      hour=23,
                      minute=59,
                      second=59,
                      microsecond=999999)
    # beteewn to date, time, or datetime
]
strpd = list(map(str, pd))
print('\n'.join(strpd))
print(str(datetime.date(2002, 12, 4).isoformat()))

print(td)
print(td - relativedelta(years=1, months=1, days=2, minutes=10))
print(td - datetime.timedelta(days=0,
                              seconds=0,
                              microseconds=0,
                              milliseconds=0,
                              minutes=0,
                              hours=0,
                              weeks=0))
print(datetime.tzinfo())
print(datetime.timezone(datetime.timedelta(hours=9)))
print(datetime.timedelta(hours=1, seconds=59).total_seconds())
print(datetime.date.fromisoformat('2019-12-04'))

print(datetime.datetime.fromisoformat('2011-11-04'))
print('what is chkjkdcosdsmmitangeee')
예제 #21
0
def main(argv):
    parser = argparse.ArgumentParser(
        description='turn a music playlist into a servable podcast')
    parser.add_argument('--input', '-i', type=argparse.FileType('r'),
        required=True, help='playlist to read')
    parser.add_argument('--output', '-o', required=True,
        help='directory to output to')
    parser.add_argument('--shuffle', action='store_true',
        help='randomise playlist')
    parser.add_argument('--prefix', required=True, help='webserver root')
    options = parser.parse_args(argv[1:])

    if not os.path.isdir(options.output):
        sys.stderr.write('%s is not a directory\n' % options.output)
        return -1

    for tool in ('ffmpeg', 'xmllint'):
        try:
            subprocess.check_call(['which', tool], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
        except subprocess.CalledProcessError:
            sys.stderr.write('%s not found\n' % tool)
            return -1

    items = []

    start_time = datetime.datetime.now() + datetime.timedelta(hours=-1)

    lines = [x.strip() for x in options.input]
    if options.shuffle:
        random.shuffle(lines)

    for index, line in enumerate(lines):
        guid = digest(line)

        path = os.path.join(options.output, '%s.mp3' % guid)

        sys.stdout.write('Encoding %s...\n' % line)
        p = subprocess.Popen(['ffmpeg', '-y', '-i', line, '-ab', '192k', path],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.communicate()
        if p.returncode != 0:
            sys.stderr.write('Failed\n')
            return -1

        size = os.stat(path).st_size

        duration = int(MP3(path).info.length)

        timestamp = formatdate(float((start_time +
            datetime.timedelta(minutes=index)).strftime('%s')),
            datetime.tzinfo())

        items.append(Item(os.path.splitext(os.path.basename(line))[0],
            '%s%s.mp3' % (options.prefix, guid), str(size), 'audio/mpeg', timestamp,
            duration='%02d:%02d' % (duration // 60, duration % 60)))

    channel = Channel('My Music', options.prefix, 'My Music',
        author=getpass.getuser())
    rss = ET.Element('rss')
    c = channel.attach(rss)
    for i in items:
        i.attach(c)
    et = ET.ElementTree(rss)
    with open(os.path.join(options.output, 'feed.xml'), 'w') as f:
        et.write(f, encoding='utf-8', xml_declaration=True)

    # Write a Lighttpd conf.
    with open(os.path.join(options.output, 'lighttpd.conf'), 'w') as f:
        f.write('server.document-root = "%s"\n'
                'server.port = 8000\n'
                'mimetype.assign = (".mp3" => "audio/mpeg")\n' %
                os.path.abspath(options.output))

    return 0
예제 #22
0
# built-in constants (CH 4)
a['CopyrightType'] = copyright
# built-in types (CH 5)
a['ClassObjectType'] = _newclass # <type 'type'>
a['ClassInstanceType'] = _newclass() # <type 'class'>
a['SetType'] = _set = set()
a['FrozenSetType'] = frozenset()
# built-in exceptions (CH 6)
a['ExceptionType'] = _exception = _function2()[0]
# string services (CH 7)
a['SREPatternType'] = _srepattern = re.compile('')
# data types (CH 8)
a['ArrayType'] = array.array("f")
a['DequeType'] = collections.deque([0])
a['DefaultDictType'] = collections.defaultdict(_function, _dict)
a['TZInfoType'] = datetime.tzinfo()
a['DateTimeType'] = datetime.datetime.today()
a['CalendarType'] = calendar.Calendar()
if not PY3:
    a['SetsType'] = sets.Set()
    a['ImmutableSetType'] = sets.ImmutableSet()
    a['MutexType'] = mutex.mutex()
# numeric and mathematical types (CH 9)
a['DecimalType'] = decimal.Decimal(1)
a['CountType'] = itertools.count(0)
# data compression and archiving (CH 12)
a['TarInfoType'] = tarfile.TarInfo()
# generic operating system services (CH 15)
a['LoggerType'] = logging.getLogger()
a['FormatterType'] = logging.Formatter() # pickle ok
a['FilterType'] = logging.Filter() # pickle ok
예제 #23
0
 def test_tz_without_normalize(self):
     tz = tzinfo()
     self.assertFalse(hasattr(tz, 'normalize'))
     self.assertTrue(localize(make_aware(datetime.utcnow(), tz), tz))
예제 #24
0
 def test_tz_without_normalize(self):
     tz = tzinfo()
     assert not hasattr(tz, 'normalize')
     assert localize(make_aware(datetime.utcnow(), tz), tz)
예제 #25
0
 def test_bad_timezone(self):
     exc = pytest.raises(TypeError, convert_to_datetime, '2009-8-1',
                         tzinfo(), None)
     assert str(exc.value) == (
         'Only pytz timezones are supported (need the localize() and '
         'normalize() methods)')
예제 #26
0
 def test_bad_timezone(self):
     exc = pytest.raises(TypeError, convert_to_datetime, '2009-8-1', tzinfo(), None)
     assert str(exc.value) == ('Only pytz timezones are supported (need the localize() and '
                               'normalize() methods)')
예제 #27
0
파일: feed.py 프로젝트: balta2ar/bzpodcast
def get_pubDate(name):
    date = datetime.fromtimestamp(os.path.getmtime(name))
    return formatdate(float(date.strftime('%s')), tzinfo())
예제 #28
0
# Standard Libraries
예제 #29
0
 def test_tzinfo(self):
     x = datetime.tzinfo()
     self.assertRaises(NotImplementedError, x.utcoffset, None)
     self.assertRaises(NotImplementedError, x.dst, None)
     self.assertRaises(NotImplementedError, x.tzname, None)
     self.assertRaises(NotImplementedError, x.fromutc, None)
예제 #30
0
os.chdir(WD)
print(os.getcwd())

#%%
import datetime as dt
#import numpy as np

dir(dt)
dt.date(year, month, day)        # class
dt.datetime(year, month, day)    # class
dt.datetime_CAPI    # reference
dt.sys              # module
dt.time()
dt.timedelta()
dt.timezone()
dt.tzinfo()

dt.date # datetime.date
type(dt.date)   # type             ???
dt.date(year, month, day)    # class
dir(dt.date)

dt.datetime
type(dt.datetime)  # type
dt.datetime(year, month, day, hour, minute, second, microsecond, tzinfo, fold)   #
dir(dt.datetime)

dt.time # datetime.time
type(dt.time)   # type
dt.time(hour, minute, second, microsecond, tzinfo, fold)
dir(dt.time)
예제 #31
0
 def test_cookie_expires_with_timezone(self):
     from datetime import tzinfo
     timestamp = datetime.utcnow().replace(tzinfo=tzinfo())
     self.assertRaises(
         ValueError, cookie, 'http://example.com', 'test', 'value',
         expires=timestamp)
예제 #32
0
 def test_tz_without_localize(self):
     tz = tzinfo()
     self.assertFalse(hasattr(tz, 'localize'))
     wtz = make_aware(datetime.utcnow(), tz)
     self.assertEqual(wtz.tzinfo, tz)
예제 #33
0
def test_tzinfo():
    x = datetime.tzinfo()
    AssertError(NotImplementedError, x.utcoffset, None)
    AssertError(NotImplementedError, x.dst, None)
    AssertError(NotImplementedError, x.tzname, None)
    AssertError(NotImplementedError, x.fromutc, None)
예제 #34
0
def test_fixedoffset_eq():
    # See https://bitbucket.org/micktwomey/pyiso8601/issues/19
    datetime.tzinfo() == iso8601.FixedOffset(2, 0, '+2:00')
예제 #35
0
def test_datetime():
    x = datetime.datetime(2006,4,11,2,28,3,99,datetime.tzinfo())
    AreEqual(x.year, 2006)
    AreEqual(x.month, 4)
    AreEqual(x.day, 11)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)
    
    datetime.datetime(2006,4,11)
    datetime.datetime(2006,4,11,2)
    datetime.datetime(2006,4,11,2,28)
    datetime.datetime(2006,4,11,2,28,3)
    datetime.datetime(2006,4,11,2,28,3,99)
    datetime.datetime(2006,4,11,2,28,3,99, None)
    
    datetime.datetime(2006,4,11,hour=2)
    datetime.datetime(2006,4,11,hour=2,minute=28)
    datetime.datetime(2006,4,11,hour=2,minute=28,second=3)
    datetime.datetime(2006,4,11,hour=2,minute=28,second=3, microsecond=99)
    datetime.datetime(2006,4,11,hour=2,minute=28,second=3, microsecond=99, tzinfo=None)
    
    datetime.datetime(1, 1, 1, 0, 0, 0, 0) #min
    datetime.datetime(9999, 12, 31, 23, 59, 59, 999999) #max
    datetime.datetime(2004, 2, 29, 16, 20, 22, 262000) #leapyear
    
    AssertError(ValueError, datetime.datetime, 2006, 2, 29, 16, 20, 22, 262000) #bad leapyear
    AssertError(ValueError, datetime.datetime, 2006, 9, 31, 16, 20, 22, 262000) #bad number of days
    
    AssertError(ValueError, datetime.datetime, 0, 1, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 0, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 0, 0, 0, 0, 0)
    
    AssertError(ValueError, datetime.datetime, -1, 1, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, -1, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, -1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, -1, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, 0, -1, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, 0, 0, -1, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, 0, 0, 0, -1)
    AssertError(ValueError, datetime.datetime, -10, -10, -10, -10, -10, -10, -10)

    AssertError(ValueError, datetime.datetime, 10000, 12, 31, 23, 59, 59, 999999)
    AssertError(ValueError, datetime.datetime, 9999, 13, 31, 23, 59, 59, 999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 32, 23, 59, 59, 999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 24, 59, 59, 999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 23, 60, 59, 999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 23, 59, 60, 999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 23, 59, 59, 1000000)
    AssertError(ValueError, datetime.datetime, 10000, 13, 32, 24, 60, 60, 1000000)
    AssertError(ValueError, datetime.datetime, 100000, 130, 320, 240, 600, 600, 10000000)
    AssertError(TypeError,  datetime.datetime, 2006, 4, 11, 2, 28, 3, 99, 1)
    
    #--------------------------------------------------------------------------
    #--Test subtraction datetime
    test_data = { ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 37, 28, 686000)) : ((0, 0, 0),(0, 0, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2007, 9, 29, 15, 37, 28, 686000)) : ((365, 0, 0),(-365, 0, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2006,10, 29, 15, 37, 28, 686000)) : ((30, 0, 0),(-30, 0, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 30, 15, 37, 28, 686000)) : ((1, 0, 0),(-1, 0, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 16, 37, 28, 686000)) : ((0, 3600, 0),(-1, 82800, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 38, 28, 686000)) : ((0, 60, 0),(-1, 86340, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 37, 29, 686000)) : ((0, 1, 0),(-1, 86399, 0)),
                  ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 37, 28, 686001)) : ((0, 0, 1),(-1, 86399, 999999)),
                  ((1, 1, 1, 0, 0, 0, 0), (1, 1, 1, 0, 0, 0, 0)) : ((0, 0, 0),(0, 0, 0)),
                  ((9999, 12, 31, 23, 59, 59, 999999), (9999, 12, 31, 23, 59, 59, 999999)) : ((0, 0, 0),(0, 0, 0))
                  }
    for key, (value0, value1) in test_data.iteritems():
        dt1 = datetime.datetime(*key[1])
        dt0 = datetime.datetime(*key[0])
        
        x = dt1 - dt0
        AreEqual(x.days, value0[0])
        AreEqual(x.seconds, value0[1])
        AreEqual(x.microseconds, value0[2])
        
        y = dt0 - dt1
        AreEqual(y.days, value1[0])
        AreEqual(y.seconds, value1[1])
        AreEqual(y.microseconds, value1[2])
        
        
    #--------------------------------------------------------------------------
    #--Test subtraction - timedelta
    test_data = { ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 0)) : (2006, 9, 29, 15, 37, 28, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (1, 0, 0)) : (2006, 9, 28, 15, 37, 28, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, 1, 0)) : (2006, 9, 29, 15, 37, 27, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 1)) : (2006, 9, 29, 15, 37, 28, 685999),
                  ((2006, 9, 29, 15, 37, 28, 686000), (1, 1, 1)) : (2006, 9, 28, 15, 37, 27, 685999),
                  
                  ((2006, 9, 29, 15, 37, 28, 686000), (-1, 0, 0)) : (2006, 9, 30, 15, 37, 28, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, -1, 0)) : (2006, 9, 29, 15, 37, 29, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, -1)) : (2006, 9, 29, 15, 37, 28, 686001),
                  ((2006, 9, 29, 15, 37, 28, 686000), (-1, -1, -1)) : (2006, 9, 30, 15, 37, 29, 686001),
                  
                  ((9999, 12, 31, 23, 59, 59, 999999), (1, 1, 1)) : (9999, 12, 30, 23, 59, 58, 999998),
                  ((9999, 12, 31, 23, 59, 59, 999999), (9999*365, 0, 0)) : (7, 8, 21, 23, 59, 59, 999999),
                  ((9999, 12, 31, 23, 59, 59, 999999), (0, 0, 0)) : (9999, 12, 31, 23, 59, 59, 999999),
                  }
    for (dt1, td0), value in test_data.iteritems():
        
        x = datetime.datetime(*dt1) - datetime.timedelta(*td0)
        AreEqual(x.year,value[0])
        AreEqual(x.month, value[1])
        AreEqual(x.day, value[2])
        AreEqual(x.hour, value[3])
        AreEqual(x.minute, value[4])
        AreEqual(x.second, value[5])
        AreEqual(x.microsecond, value[6])
    
    
    #--------------------------------------------------------------------------
    #--Test addition
    test_data = { ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 0)) : (2006, 9, 29, 15, 37, 28, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (1, 0, 0)) : (2006, 9, 30, 15, 37, 28, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, 1, 0)) : (2006, 9, 29, 15, 37, 29, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 1)) : (2006, 9, 29, 15, 37, 28, 686001),
                  ((2006, 9, 29, 15, 37, 28, 686000), (1, 1, 1)) : (2006, 9, 30, 15, 37, 29, 686001),
                  
                  ((2006, 9, 29, 15, 37, 28, 686000), (-1, 0, 0)) : (2006, 9, 28, 15, 37, 28, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, -1, 0)) : (2006, 9, 29, 15, 37, 27, 686000),
                  ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, -1)) : (2006, 9, 29, 15, 37, 28, 685999),
                  ((2006, 9, 29, 15, 37, 28, 686000), (-1, -1, -1)) : (2006, 9, 28, 15, 37, 27, 685999),
    
                  ((9999, 12, 31, 23, 59, 59, 999999), (-1, -1, -1)) : (9999, 12, 30, 23, 59, 58, 999998),
                  ((9999, 12, 31, 23, 59, 59, 999999), (-9999*365, 0, 0)) : (7, 8, 21, 23, 59, 59, 999999),
                  ((9999, 12, 31, 23, 59, 59, 999999), (0, 0, 0)) : (9999, 12, 31, 23, 59, 59, 999999),
                  }
    for (dt1, td0), value in test_data.iteritems():
        
        x = datetime.datetime(*dt1) + datetime.timedelta(*td0)
        AreEqual(x.year,value[0])
        AreEqual(x.month, value[1])
        AreEqual(x.day, value[2])
        AreEqual(x.hour, value[3])
        AreEqual(x.minute, value[4])
        AreEqual(x.second, value[5])
        AreEqual(x.microsecond, value[6])
        
        #CodePlex Work Item 4861
        x = datetime.timedelta(*td0) + datetime.datetime(*dt1)
        AreEqual(x.year,value[0])
        AreEqual(x.month, value[1])
        AreEqual(x.day, value[2])
        AreEqual(x.hour, value[3])
        AreEqual(x.minute, value[4])
        AreEqual(x.second, value[5])
        AreEqual(x.microsecond, value[6])
    
    #--------------------------------------------------------------------------
    
    #today
    t0 = datetime.datetime.today()
    t1 = datetime.datetime.today()
    AreEqual(type(t0), datetime.datetime)
    Assert(t0<=t1)
    
    #now
    from time import sleep
    t0 = datetime.datetime.now()
    sleep(1)
    t1 = datetime.datetime.now()
    AreEqual(type(t0), datetime.datetime)
    Assert(t1>t0)
    datetime.datetime.now(None)
    
    #now
    t0 = datetime.datetime.utcnow()
    sleep(1)
    t1 = datetime.datetime.utcnow()
    AreEqual(type(t0), datetime.datetime)
    Assert(t1>t0)
    
    #fromtimestamp
    #Merlin Work Item 148717
    x = datetime.datetime.fromtimestamp(1000000000.0)
    AreEqual(x.year, 2001)
    AreEqual(x.month, 9)
    AreEqual(x.day, 8)
    #CodePlex 4862
    #AreEqual(x.hour, 18)
    AreEqual(x.minute, 46)
    AreEqual(x.second, 40)
    
    x = datetime.datetime.fromtimestamp(1000000000)
    AreEqual(x.year, 2001)
    AreEqual(x.month, 9)
    AreEqual(x.day, 8)
    #CodePlex Work Item 4862
    #AreEqual(x.hour, 18)
    AreEqual(x.minute, 46)
    AreEqual(x.second, 40)
    
    #fromordinal
    x = datetime.datetime.fromordinal(1234567)
    AreEqual(x.year, 3381)
    AreEqual(x.month, 2)
    AreEqual(x.day, 16)
    
    #fromtimestamp
    x = datetime.datetime.utcfromtimestamp(1000000000.0)
    AreEqual(x.year, 2001)
    AreEqual(x.month, 9)
    AreEqual(x.day, 9)
    #CodePlex 4862
    #AreEqual(x.hour, 1)
    AreEqual(x.minute, 46)
    AreEqual(x.second, 40)
    
    #combine
    x = datetime.datetime.combine(datetime.date(2005, 3, 22), datetime.time(2,28,3,99))
    y = datetime.datetime(2005, 3, 22, 2, 28, 3, 99)
    AreEqual(x, y)
    
    #strptime - new for Python 2.5. No need to test
    
    #min
    x = datetime.datetime.min
    AreEqual(x.year, datetime.MINYEAR)
    AreEqual(x.month, 1)
    AreEqual(x.day, 1)
    AreEqual(x.hour, 0)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    #CodePlex Work Item 4863
    y = datetime.datetime(datetime.MINYEAR, 1, 1)
    AreEqual(x, y)
    
    #max
    #CodePlex Work Item 4864
    x = datetime.datetime.max
    AreEqual(x.year, datetime.MAXYEAR)
    AreEqual(x.month, 12)
    AreEqual(x.day, 31)
    AreEqual(x.hour, 23)
    AreEqual(x.minute, 59)
    AreEqual(x.second, 59)
    AreEqual(x.microsecond, 999999)
    #CodePlex Work Item 4865
    y = datetime.datetime(datetime.MAXYEAR, 12, 31, 23, 59, 59, 999999, None)
    AreEqual(x, y)
    
    #resolution
    #CodePlex Work Item 4866
    x = datetime.datetime.resolution
    AreEqual(x.days, 0)
    AreEqual(x.seconds, 0)
    AreEqual(x.microseconds, 1)
    
    #equality
    x = datetime.datetime(2005, 3, 22)
    y = x
    Assert(x==y)
    y = datetime.datetime(2005, 3, 23)
    Assert(not(x==y))
    Assert(x==datetime.datetime(2005, 3, 22))
    
    #inequality
    x = datetime.datetime(2005, 3, 22)
    y = None
    Assert(x!=y)
    y = datetime.datetime(2005, 3, 23)
    Assert(x!=y)
    
    #ge/le/gt/lt/eq/ne
    #CodePlex Work Item 4860
    #x_args = [2006, 9, 29, 15, 37, 28, 686000]
    x_args = [2006, 9, 29, 15, 37, 28]
    x = datetime.datetime(*x_args)
    for i in range(len(x_args)):
        
        y_args = x_args[0:]
        y_args [i] = y_args[i]+1
        y = datetime.datetime(*y_args)
        x_copy = datetime.datetime(*x_args)
        
        Assert(y>=x)
        Assert(x<=y)
        Assert(x<y)
        Assert(y>x)
        Assert(not x>y)
        Assert(not x>y)
        Assert(not x==y)
        Assert(x!=y)
        
        Assert(x==x_copy)
        Assert(x_copy >= x)
        Assert(x_copy <= x)
        
    #date and time
    date = datetime.date(2005, 3, 23)
    time = datetime.time(2,28,3,99)
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    AreEqual(x.date(), date)
    #CodePlex Work Item 4860
    AreEqual(x.time(), time)
    
    #timetz
    #CodePlex Work Item 4860
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    time = datetime.time(2,28,3,99)
    AreEqual(x.timetz(), time)
    
    #replace
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    y = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)

    z = x.replace(year=1000)
    AreEqual(y, x)
    AreEqual(z.year, 1000)

    z = x.replace(month=7)
    AreEqual(y, x)
    AreEqual(z.month, 7)
    
    z = x.replace(day=12)
    AreEqual(y, x)
    AreEqual(z.day, 12)

    z = x.replace(hour=3)
    AreEqual(y, x)
    AreEqual(z.hour, 3)

    z = x.replace(minute=5)
    AreEqual(y, x)
    AreEqual(z.minute, 5)

    z = x.replace(second=25)
    AreEqual(y, x)
    AreEqual(z.second, 25)
    
    #CodePlex Work Item 4860
    z = x.replace(microsecond=250)
    AreEqual(y, x)
    AreEqual(z.microsecond, 250)
    
    z = x.replace(year=1000, month=7, day=12, hour=3, minute=5, second=25, microsecond=250)
    AreEqual(y, x)
    AreEqual(z.year, 1000)
    AreEqual(z.month, 7)
    AreEqual(z.day, 12)
    AreEqual(z.hour, 3)
    AreEqual(z.minute, 5)
    AreEqual(z.second, 25)
    #CodePlex Work Item 4860
    AreEqual(z.microsecond, 250)
    
    #astimezone
    #TODO
    #x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    #x.astimezone(...)
    
    #utcoffset
    x = datetime.datetime(2005, 3, 23, 2,28,3,99,None)
    AreEqual(x.utcoffset(), None)
    
    #dst
    x = datetime.datetime(2005, 3, 23,2,28,3,99,None)
    AreEqual(x.dst(), None)
    
    #tzname
    x = datetime.datetime(2005, 3, 23, 2,28,3,99,None)
    AreEqual(x.tzname(), None)
    
    #timetuple
    AreEqual(datetime.datetime(2005, 3, 23,2,28,3,99,None).timetuple(), (2005, 3, 23, 2, 28, 3, 2, 82, -1))
    
    #utctimetuple
    AreEqual(datetime.datetime(2005, 3, 23,2,28,3,99,None).utctimetuple(), (2005, 3, 23, 2, 28, 3, 2, 82, 0))
    
    #toordinal
    AreEqual(datetime.datetime(2005, 3, 23,2,28,3,99,None).toordinal(), 732028)

    #weekday
    AreEqual(datetime.datetime(2005, 3, 23,2,28,3,99,None).weekday(), 2)
    
    #isocalendar
    x = datetime.datetime(2005, 3, 22,2,28,3,99,None).isocalendar()
    AreEqual(x[0], 2005)
    AreEqual(x[1], 12)
    AreEqual(x[2], 2)
    
    #isoformat
    x = datetime.datetime(2005, 3, 22, 2,28,3,99,None).isoformat()
    AreEqual(x, '2005-03-22T02:28:03.000099')
    
    #isoweekday
    AreEqual(datetime.datetime(2005, 3, 22, 2,28,3,99,None).isoweekday(), 2)
    
    #ctime
    AreEqual(datetime.datetime(2005, 3, 22, 2,28,3,99,None).ctime(), 'Tue Mar 22 02:28:03 2005')
    
    
    #strftime
    x = datetime.datetime(2005, 3, 22, 2,28,3,99,None)
    AreEqual(x.strftime("%y-%a-%b"), "05-Tue-Mar")
    AreEqual(x.strftime("%Y-%A-%B"), "2005-Tuesday-March")
    AreEqual(x.strftime("%Y%m%d"), '20050322')
    AreEqual(x.strftime("%I:%M:%S"), "02:28:03")
    #Similar to Merlin Work Item 148470
    AreEqual(x.strftime("%H:%M:%S"), "02:28:03")
    #Similar to Merlin Work Item 148470
    if not is_silverlight:
        AreEqual(x.strftime("%a %A %b %B %c %d %H %I %j %m %M %p %S %U %w %W %x %X %y %Y %Z %%"), "Tue Tuesday Mar March 03/22/05 02:28:03 22 02 02 081 03 28 AM 03 12 2 12 03/22/05 02:28:03 05 2005  %")
예제 #36
0
 def test_bad_timezone_type(self):
     exc = pytest.raises(TypeError, astimezone, tzinfo())
     assert 'Only timezones from the pytz library are supported' in str(
         exc.value)
예제 #37
0
def test_time():
    #basic sanity checks
    x = datetime.time(2,28,3,99,datetime.tzinfo())
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)
    
    x = datetime.time(2,28,3,99,None)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)
    
    x = datetime.time(2,28,3,99)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)
    
    x = datetime.time(2,28,3)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 0)
    
    x = datetime.time(2,28)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    
    x = datetime.time(2)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    
    x = datetime.time()
    AreEqual(x.hour, 0)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    
    datetime.time(0, 0, 0, 0) #min
    datetime.time(23, 59, 59, 999999) #max
    
    #negative cases
    #CodePlex Work Item 5143
    AssertError(ValueError, datetime.time, -1, 0, 0, 0)
    AssertError(ValueError, datetime.time, 0, -1, 0, 0)
    AssertError(ValueError, datetime.time, 0, 0, -1, 0)
    AssertError(ValueError, datetime.time, 0, 0, 0, -1)
    AssertError(ValueError, datetime.time, -10, -10, -10, -10)
    
    #CodePlex Work Item 5143
    AssertError(ValueError, datetime.time, 24, 59, 59, 999999)
    AssertError(ValueError, datetime.time, 23, 60, 59, 999999)
    AssertError(ValueError, datetime.time, 23, 59, 60, 999999)
    AssertError(ValueError, datetime.time, 23, 59, 59, 1000000)
    AssertError(ValueError, datetime.time, 24, 60, 60, 1000000)
    AssertError(ValueError, datetime.time, 240, 600, 600, 10000000)
    
    #min
    x = datetime.time.min
    AreEqual(x.hour, 0)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    #max
    x = datetime.time.max
    AreEqual(x.hour, 23)
    AreEqual(x.minute, 59)
    AreEqual(x.second, 59)
    AreEqual(x.microsecond, 999999)
    
    #resolution
    #CodePlex Work Item 5145
    x = datetime.time.resolution
    AreEqual(repr(x), 'datetime.timedelta(0, 0, 1)')
    
    #equality
    x = datetime.time(1, 2, 33, 444)
    y = x
    Assert(x==y)
    y = datetime.time(1, 2, 33, 445)
    Assert(not(x==y))
    Assert(x==datetime.time(1, 2, 33, 444))
    
    #inequality
    x = datetime.time(1, 2, 33, 444)
    y = None
    Assert(x!=y)
    y = datetime.time(1, 2, 33, 445)
    Assert(x!=y)
    
    #ge
    Assert(datetime.time(1, 2, 33, 444) >= datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 445) >= datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 446) >= datetime.time(1, 2, 33, 444))
    Assert(not (datetime.time(1, 2, 33, 443) >= datetime.time(1, 2, 33, 444)))
    Assert(not (datetime.time(1, 2, 33, 442) >= datetime.time(1, 2, 33, 444)))
    
    #le
    Assert(datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 445))
    Assert(datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 446))
    Assert(not (datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 443)))
    Assert(not (datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 442)))
    
    #gt
    Assert(not (datetime.time(1, 2, 33, 444) > datetime.time(1, 2, 33, 444)))
    Assert(datetime.time(1, 2, 33, 445) > datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 446) > datetime.time(1, 2, 33, 444))
    Assert(not (datetime.time(1, 2, 33, 443) > datetime.time(1, 2, 33, 444)))
    Assert(not (datetime.time(1, 2, 33, 442) > datetime.time(1, 2, 33, 444)))
    
    #lt
    Assert(not(datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 444)))
    Assert(datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 445))
    Assert(datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 446))
    Assert(not (datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 443)))
    Assert(not (datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 442)))
    
    #hash
    x = datetime.time(1, 2, 33, 444)
    Assert(x.__hash__()!=None)
    
    #bool
    Assert(datetime.time(0, 0, 0, 1))
    #CodePlex Work Item 5139
    Assert(not (datetime.time(0, 0, 0, 0)))
    
    #replace
    x = datetime.time(1, 2, 33, 444)
    y = datetime.time(1, 2, 33, 444)

    z = x.replace(hour=3)
    AreEqual(y, x)
    AreEqual(z.hour, 3)

    z = x.replace(minute=5)
    AreEqual(y, x)
    AreEqual(z.minute, 5)

    z = x.replace(second=25)
    AreEqual(y, x)
    AreEqual(z.second, 25)
    
    z = x.replace(microsecond=250)
    AreEqual(y, x)
    AreEqual(z.microsecond, 250)
    
    z = x.replace(hour=3, minute=5, second=25, microsecond=250)
    AreEqual(y, x)
    AreEqual(z.hour, 3)
    AreEqual(z.minute, 5)
    AreEqual(z.second, 25)
    AreEqual(z.microsecond, 250)
    
    #isoformat
    #CodePlex Work Item 5146
    x = datetime.time(2,28,3,99).isoformat()
    AreEqual(x, '02:28:03.000099')
    
    #strftime
    x = datetime.time(13,28,3,99)
    AreEqual(x.strftime("%I:%M:%S"), "01:28:03")
    AreEqual(x.strftime("%H:%M:%S"), "13:28:03")
    
    #utcoffset
    #CodePlex Work Item 5147
    x = datetime.time(2,28,3,99,None)
    AreEqual(x.utcoffset(), None)
    
    #dst
    x = datetime.time(2,28,3,99,None)
    AreEqual(x.dst(), None)
    
    #tzname
    #CodePlex Work Item 5148
    x = datetime.time(2,28,3,99,None)
    AreEqual(x.tzname(), None)
예제 #38
0
import datetime

ctime = datetime.datetime.now()
print ctime

nextweek = ctime + datetime.timedelta(days=7)
nw = nextweek.strftime(r"%d/%b/%Y  %H:%M:%S")
#print nextweek
print nw
previousweek = ctime - datetime.timedelta(days=7)
pw = previousweek.strftime(r"%d/%b/%Y  %H:%M:%S")
#print previousweek
print pw
print datetime.MAXYEAR
print datetime.MINYEAR
print datetime.tzinfo()
print datetime.date.today()
print datetime.time.tzinfo()
예제 #39
0
# built-in constants (CH 4)
a['CopyrightType'] = copyright
# built-in types (CH 5)
a['ClassObjectType'] = _newclass  # <type 'type'>
a['ClassInstanceType'] = _newclass()  # <type 'class'>
a['SetType'] = _set = set()
a['FrozenSetType'] = frozenset()
# built-in exceptions (CH 6)
a['ExceptionType'] = _exception = _function2()[0]
# string services (CH 7)
a['SREPatternType'] = _srepattern = re.compile('')
# data types (CH 8)
a['ArrayType'] = array.array("f")
a['DequeType'] = collections.deque([0])
a['DefaultDictType'] = collections.defaultdict(_function, _dict)
a['TZInfoType'] = datetime.tzinfo()
a['DateTimeType'] = datetime.datetime.today()
a['CalendarType'] = calendar.Calendar()
if not PY3:
    a['SetsType'] = sets.Set()
    a['ImmutableSetType'] = sets.ImmutableSet()
    a['MutexType'] = mutex.mutex()
# numeric and mathematical types (CH 9)
a['DecimalType'] = decimal.Decimal(1)
a['CountType'] = itertools.count(0)
# data compression and archiving (CH 12)
a['TarInfoType'] = tarfile.TarInfo()
# generic operating system services (CH 15)
a['LoggerType'] = logging.getLogger()
a['FormatterType'] = logging.Formatter()  # pickle ok
a['FilterType'] = logging.Filter()  # pickle ok
예제 #40
0
from email.utils import formatdate
from datetime import datetime, timedelta, tzinfo

"""
prints the current time and time from three hours ago in RFC 2822 (email) format
stu@sente ~ $ python rfc2822.py
Wed, 21 Dec 2011 16:45:46 -0500
Wed, 21 Dec 2011 13:45:46 -0500
"""

now = datetime.now()
delta = timedelta(hours=-3)

newdate = now + delta

print formatdate(float(now.strftime("%s")),tzinfo())
print formatdate(float(newdate.strftime("%s")),tzinfo())
예제 #41
0
# (C) 2017 The MITRE Corporation.

import datetime

from mongoengine.base import TopLevelDocumentMetaclass
from mongoengine import DoesNotExist
from mongoengine.fields import (DateTimeField, DictField, ListField,
                                ReferenceField, EmbeddedDocument,
                                EmbeddedDocumentField, DynamicField,
                                StringField, DecimalField)

from app.cascade.database import UniqueDocument
from app.cascade.data_model.host import Host
from .query import QueryTerm, CompareString, FieldQuery, EmptyQuery, EmbeddedQueryTerm

utc_tz = datetime.tzinfo(None, 0)

event_lookup = {}
""":type: dict[str, DataModelEventMeta | DataModelEvent] """


class EventState(EmbeddedDocument):
    meta = {'allow_inheritance': True}
    # Expose these fields now for indexing
    hostname = DynamicField()
    ppid = DynamicField()
    pid = DynamicField()
    fqdn = DynamicField()


class DataModelEventMeta(TopLevelDocumentMetaclass):
예제 #42
0
 def test_tz_without_localize(self):
     tz = tzinfo()
     self.assertFalse(hasattr(tz, 'localize'))
     wtz = make_aware(datetime.utcnow(), tz)
     self.assertEqual(wtz.tzinfo, tz)
예제 #43
0
파일: datetime.py 프로젝트: 18600597055/hue
    if 1 < value < 60 and offset == CALENDAR_WINDOWS_1900:
        value += 1
    parts = list(jd2gcal(MJD_0, value + offset - MJD_0))
    _, fraction = divmod(value, 1)
    jumped = (parts[-1] == 0 and fraction > 0)
    diff = datetime.timedelta(days=fraction)

    if 0 < abs(value) < 1:
        return days_to_time(diff)
    if not jumped:
        return datetime.datetime(*parts[:3]) + diff
    else:
        return datetime.datetime(*parts[:3] + [0])


UTC = tzinfo(timedelta(0), offset=0)

class GMT(tzinfo):

    def utcoffset(self, dt):
        return timedelta(0)

    def dst(self, dt):
        return timedelta(0)

    def tzname(self,dt):
        return "GMT"

try:
    from datetime import timezone
    UTC = timezone(timedelta(0))
예제 #44
0
from services.models import Message, Usage, FeatureUsage, Location
from rest_framework import response, viewsets
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticatedOrReadOnly, AllowAny
from services.serializer import MessageSerializer, UsageSerializer, FeatureSerializer, LocationSerializer
import django_filters
from rest_framework.reverse import reverse
from django.http import HttpResponse
import json
import datetime
import hashlib
import settings
import services.plots as plotsfile

OS_NAMES = ['Linux', 'Windows NT', 'Darwin']
UTC = datetime.tzinfo('UTC')
LOCALHOST_IP = "127.0.0.1"


def createLocation(request):
    # Assume this is a proxied request
    ip_addr = request.META.get('HTTP_X_FORWARDED_FOR', None)
    # ipinfo's API has a bad JSON format for 127.0.0.1 requests.
    # This changes the loopback IP to a random address for testing.
    # Location should have IP as a unique field. Change the IP
    # or you won't be able to add the test value more than once.
    if ip_addr is None or ip_addr == LOCALHOST_IP:
        return None
    ip_hash = hashlib.md5(ip_addr).hexdigest()
    if len(Location.objects.all().filter(ip=ip_hash)) == 0:
        # check for the HASHED ip in the database. If it isn't present,
예제 #45
0
파일: test_time.py 프로젝트: wooyek/celery
 def test_tz_without_localize(self):
     tz = tzinfo()
     assert not hasattr(tz, 'localize')
     wtz = make_aware(datetime.utcnow(), tz)
     assert wtz.tzinfo == tz
예제 #46
0
파일: Time.py 프로젝트: onyb/dune
def get_current_local_time():
    return formatdate(time(), tzinfo())
예제 #47
0
파일: test_time.py 프로젝트: wooyek/celery
 def test_tz_without_normalize(self):
     tz = tzinfo()
     assert not hasattr(tz, 'normalize')
     assert localize(make_aware(datetime.utcnow(), tz), tz)
예제 #48
0
 def test_tz_without_localize(self):
     tz = tzinfo()
     assert not hasattr(tz, 'localize')
     wtz = make_aware(datetime.utcnow(), tz)
     assert wtz.tzinfo == tz
예제 #49
0
def test_tzinfo():
    x = datetime.tzinfo()
    AssertError(NotImplementedError, x.utcoffset, None)
    AssertError(NotImplementedError, x.dst, None)
    AssertError(NotImplementedError, x.tzname, None)
    AssertError(NotImplementedError, x.fromutc, None)
예제 #50
0
파일: cast.py 프로젝트: Smattr/mattutils
def main(argv):
    parser = argparse.ArgumentParser(
        description='turn a music playlist into a servable podcast')
    parser.add_argument('--input', '-i', type=argparse.FileType('r'),
        required=True, help='playlist to read')
    parser.add_argument('--output', '-o', required=True,
        help='directory to output to')
    parser.add_argument('--shuffle', action='store_true',
        help='randomise playlist')
    parser.add_argument('--prefix', required=True, help='webserver root')
    options = parser.parse_args(argv[1:])

    if not os.path.isdir(options.output):
        sys.stderr.write('%s is not a directory\n' % options.output)
        return -1

    for tool in ('ffmpeg', 'xmllint'):
        try:
            subprocess.check_call(['which', tool], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
        except subprocess.CalledProcessError:
            sys.stderr.write('%s not found\n' % tool)
            return -1

    items = []

    start_time = datetime.datetime.now() + datetime.timedelta(hours=-1)

    lines = [x.strip() for x in options.input]
    if options.shuffle:
        random.shuffle(lines)

    for index, line in enumerate(lines):
        guid = digest(line)

        path = os.path.join(options.output, '%s.mp3' % guid)

        sys.stdout.write('Encoding %s...\n' % line)
        p = subprocess.Popen(['ffmpeg', '-y', '-i', line, '-ab', '192k', path],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.communicate()
        if p.returncode != 0:
            sys.stderr.write('Failed\n')
            return -1

        size = os.stat(path).st_size

        duration = int(MP3(path).info.length)

        timestamp = formatdate(float((start_time +
            datetime.timedelta(minutes=index)).strftime('%s')),
            datetime.tzinfo())

        items.append(Item(os.path.splitext(os.path.basename(line))[0],
            '%s%s.mp3' % (options.prefix, guid), str(size), 'audio/mpeg', timestamp,
            duration='%02d:%02d' % (duration // 60, duration % 60)))

    channel = Channel('My Music', options.prefix, 'My Music',
        author=getpass.getuser())
    rss = ET.Element('rss')
    rss.attrib['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
    c = channel.attach(rss)
    for i in items:
        i.attach(c)
    et = ET.ElementTree(rss)
    et.write('feed.xml', encoding='UTF-8', xml_declaration=True)

    # Validate the XML we just generated is legit.
    subprocess.call(['xmllint', '--noout', 'feed.xml'])

    # Write a Lighttpd conf.
    with open(os.path.join(options.output, 'lighttpd.conf'), 'w') as f:
        f.write('server.document-root = "%s"\n'
                'server.port = 8000\n'
                'mimetype.assign = (".mp3" => "audio/mpeg")\n' %
                os.path.abspath(options.output))

    return 0
예제 #51
0
def test_datetime():
    x = datetime.datetime(2006, 4, 11, 2, 28, 3, 99, datetime.tzinfo())
    AreEqual(x.year, 2006)
    AreEqual(x.month, 4)
    AreEqual(x.day, 11)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)

    datetime.datetime(2006, 4, 11)
    datetime.datetime(2006, 4, 11, 2)
    datetime.datetime(2006, 4, 11, 2, 28)
    datetime.datetime(2006, 4, 11, 2, 28, 3)
    datetime.datetime(2006, 4, 11, 2, 28, 3, 99)
    datetime.datetime(2006, 4, 11, 2, 28, 3, 99, None)

    datetime.datetime(2006, 4, 11, hour=2)
    datetime.datetime(2006, 4, 11, hour=2, minute=28)
    datetime.datetime(2006, 4, 11, hour=2, minute=28, second=3)
    datetime.datetime(2006, 4, 11, hour=2, minute=28, second=3, microsecond=99)
    datetime.datetime(2006,
                      4,
                      11,
                      hour=2,
                      minute=28,
                      second=3,
                      microsecond=99,
                      tzinfo=None)

    datetime.datetime(1, 1, 1, 0, 0, 0, 0)  #min
    datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)  #max
    datetime.datetime(2004, 2, 29, 16, 20, 22, 262000)  #leapyear

    AssertError(ValueError, datetime.datetime, 2006, 2, 29, 16, 20, 22,
                262000)  #bad leapyear
    AssertError(ValueError, datetime.datetime, 2006, 9, 31, 16, 20, 22,
                262000)  #bad number of days

    AssertError(ValueError, datetime.datetime, 0, 1, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 0, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 0, 0, 0, 0, 0)

    AssertError(ValueError, datetime.datetime, -1, 1, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, -1, 1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, -1, 0, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, -1, 0, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, 0, -1, 0, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, 0, 0, -1, 0)
    AssertError(ValueError, datetime.datetime, 1, 1, 1, 0, 0, 0, -1)
    AssertError(ValueError, datetime.datetime, -10, -10, -10, -10, -10, -10,
                -10)

    AssertError(ValueError, datetime.datetime, 10000, 12, 31, 23, 59, 59,
                999999)
    AssertError(ValueError, datetime.datetime, 9999, 13, 31, 23, 59, 59,
                999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 32, 23, 59, 59,
                999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 24, 59, 59,
                999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 23, 60, 59,
                999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 23, 59, 60,
                999999)
    AssertError(ValueError, datetime.datetime, 9999, 12, 31, 23, 59, 59,
                1000000)
    AssertError(ValueError, datetime.datetime, 10000, 13, 32, 24, 60, 60,
                1000000)
    AssertError(ValueError, datetime.datetime, 100000, 130, 320, 240, 600, 600,
                10000000)
    AssertError(TypeError, datetime.datetime, 2006, 4, 11, 2, 28, 3, 99, 1)

    #--------------------------------------------------------------------------
    #--Test subtraction datetime
    test_data = {
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 37, 28, 686000)):
        ((0, 0, 0), (0, 0, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2007, 9, 29, 15, 37, 28, 686000)):
        ((365, 0, 0), (-365, 0, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 10, 29, 15, 37, 28, 686000)):
        ((30, 0, 0), (-30, 0, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 30, 15, 37, 28, 686000)):
        ((1, 0, 0), (-1, 0, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 16, 37, 28, 686000)):
        ((0, 3600, 0), (-1, 82800, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 38, 28, 686000)):
        ((0, 60, 0), (-1, 86340, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 37, 29, 686000)):
        ((0, 1, 0), (-1, 86399, 0)),
        ((2006, 9, 29, 15, 37, 28, 686000), (2006, 9, 29, 15, 37, 28, 686001)):
        ((0, 0, 1), (-1, 86399, 999999)),
        ((1, 1, 1, 0, 0, 0, 0), (1, 1, 1, 0, 0, 0, 0)): ((0, 0, 0), (0, 0, 0)),
        ((9999, 12, 31, 23, 59, 59, 999999), (9999, 12, 31, 23, 59, 59, 999999)):
        ((0, 0, 0), (0, 0, 0))
    }
    for key, (value0, value1) in test_data.iteritems():
        dt1 = datetime.datetime(*key[1])
        dt0 = datetime.datetime(*key[0])

        x = dt1 - dt0
        AreEqual(x.days, value0[0])
        AreEqual(x.seconds, value0[1])
        AreEqual(x.microseconds, value0[2])

        y = dt0 - dt1
        AreEqual(y.days, value1[0])
        AreEqual(y.seconds, value1[1])
        AreEqual(y.microseconds, value1[2])

    #--------------------------------------------------------------------------
    #--Test subtraction - timedelta
    test_data = {
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 0)):
        (2006, 9, 29, 15, 37, 28, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (1, 0, 0)):
        (2006, 9, 28, 15, 37, 28, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 1, 0)):
        (2006, 9, 29, 15, 37, 27, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 1)):
        (2006, 9, 29, 15, 37, 28, 685999),
        ((2006, 9, 29, 15, 37, 28, 686000), (1, 1, 1)): (2006, 9, 28, 15, 37,
                                                         27, 685999),
        ((2006, 9, 29, 15, 37, 28, 686000), (-1, 0, 0)): (2006, 9, 30, 15, 37,
                                                          28, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, -1, 0)): (2006, 9, 29, 15, 37,
                                                          29, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, -1)): (2006, 9, 29, 15, 37,
                                                          28, 686001),
        ((2006, 9, 29, 15, 37, 28, 686000), (-1, -1, -1)): (2006, 9, 30, 15,
                                                            37, 29, 686001),
        ((9999, 12, 31, 23, 59, 59, 999999), (1, 1, 1)): (9999, 12, 30, 23, 59,
                                                          58, 999998),
        ((9999, 12, 31, 23, 59, 59, 999999), (9999 * 365, 0, 0)):
        (7, 8, 21, 23, 59, 59, 999999),
        ((9999, 12, 31, 23, 59, 59, 999999), (0, 0, 0)): (9999, 12, 31, 23, 59,
                                                          59, 999999),
    }
    for (dt1, td0), value in test_data.iteritems():

        x = datetime.datetime(*dt1) - datetime.timedelta(*td0)
        AreEqual(x.year, value[0])
        AreEqual(x.month, value[1])
        AreEqual(x.day, value[2])
        AreEqual(x.hour, value[3])
        AreEqual(x.minute, value[4])
        AreEqual(x.second, value[5])
        AreEqual(x.microsecond, value[6])

    #--------------------------------------------------------------------------
    #--Test addition
    test_data = {
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 0)):
        (2006, 9, 29, 15, 37, 28, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (1, 0, 0)):
        (2006, 9, 30, 15, 37, 28, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 1, 0)):
        (2006, 9, 29, 15, 37, 29, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, 1)):
        (2006, 9, 29, 15, 37, 28, 686001),
        ((2006, 9, 29, 15, 37, 28, 686000), (1, 1, 1)): (2006, 9, 30, 15, 37,
                                                         29, 686001),
        ((2006, 9, 29, 15, 37, 28, 686000), (-1, 0, 0)): (2006, 9, 28, 15, 37,
                                                          28, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, -1, 0)): (2006, 9, 29, 15, 37,
                                                          27, 686000),
        ((2006, 9, 29, 15, 37, 28, 686000), (0, 0, -1)): (2006, 9, 29, 15, 37,
                                                          28, 685999),
        ((2006, 9, 29, 15, 37, 28, 686000), (-1, -1, -1)): (2006, 9, 28, 15,
                                                            37, 27, 685999),
        ((9999, 12, 31, 23, 59, 59, 999999), (-1, -1, -1)): (9999, 12, 30, 23,
                                                             59, 58, 999998),
        ((9999, 12, 31, 23, 59, 59, 999999), (-9999 * 365, 0, 0)):
        (7, 8, 21, 23, 59, 59, 999999),
        ((9999, 12, 31, 23, 59, 59, 999999), (0, 0, 0)): (9999, 12, 31, 23, 59,
                                                          59, 999999),
    }
    for (dt1, td0), value in test_data.iteritems():

        x = datetime.datetime(*dt1) + datetime.timedelta(*td0)
        AreEqual(x.year, value[0])
        AreEqual(x.month, value[1])
        AreEqual(x.day, value[2])
        AreEqual(x.hour, value[3])
        AreEqual(x.minute, value[4])
        AreEqual(x.second, value[5])
        AreEqual(x.microsecond, value[6])

        #CodePlex Work Item 4861
        x = datetime.timedelta(*td0) + datetime.datetime(*dt1)
        AreEqual(x.year, value[0])
        AreEqual(x.month, value[1])
        AreEqual(x.day, value[2])
        AreEqual(x.hour, value[3])
        AreEqual(x.minute, value[4])
        AreEqual(x.second, value[5])
        AreEqual(x.microsecond, value[6])

    #--------------------------------------------------------------------------

    #today
    t0 = datetime.datetime.today()
    t1 = datetime.datetime.today()
    AreEqual(type(t0), datetime.datetime)
    Assert(t0 <= t1)

    #now
    from time import sleep
    t0 = datetime.datetime.now()
    sleep(1)
    t1 = datetime.datetime.now()
    AreEqual(type(t0), datetime.datetime)
    Assert(t1 > t0)
    datetime.datetime.now(None)

    #now
    t0 = datetime.datetime.utcnow()
    sleep(1)
    t1 = datetime.datetime.utcnow()
    AreEqual(type(t0), datetime.datetime)
    Assert(t1 > t0)

    #fromtimestamp
    #Merlin Work Item 148717
    x = datetime.datetime.fromtimestamp(1000000000.0)
    AreEqual(x.year, 2001)
    AreEqual(x.month, 9)
    AreEqual(x.day, 8)
    #CodePlex 4862
    #AreEqual(x.hour, 18)
    AreEqual(x.minute, 46)
    AreEqual(x.second, 40)

    x = datetime.datetime.fromtimestamp(1000000000)
    AreEqual(x.year, 2001)
    AreEqual(x.month, 9)
    AreEqual(x.day, 8)
    #CodePlex Work Item 4862
    #AreEqual(x.hour, 18)
    AreEqual(x.minute, 46)
    AreEqual(x.second, 40)

    #fromordinal
    x = datetime.datetime.fromordinal(1234567)
    AreEqual(x.year, 3381)
    AreEqual(x.month, 2)
    AreEqual(x.day, 16)

    #fromtimestamp
    x = datetime.datetime.utcfromtimestamp(1000000000.0)
    AreEqual(x.year, 2001)
    AreEqual(x.month, 9)
    AreEqual(x.day, 9)
    #CodePlex 4862
    #AreEqual(x.hour, 1)
    AreEqual(x.minute, 46)
    AreEqual(x.second, 40)

    #combine
    x = datetime.datetime.combine(datetime.date(2005, 3, 22),
                                  datetime.time(2, 28, 3, 99))
    y = datetime.datetime(2005, 3, 22, 2, 28, 3, 99)
    AreEqual(x, y)

    #strptime - new for Python 2.5. No need to test

    #min
    x = datetime.datetime.min
    AreEqual(x.year, datetime.MINYEAR)
    AreEqual(x.month, 1)
    AreEqual(x.day, 1)
    AreEqual(x.hour, 0)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    #CodePlex Work Item 4863
    y = datetime.datetime(datetime.MINYEAR, 1, 1)
    AreEqual(x, y)

    #max
    #CodePlex Work Item 4864
    x = datetime.datetime.max
    AreEqual(x.year, datetime.MAXYEAR)
    AreEqual(x.month, 12)
    AreEqual(x.day, 31)
    AreEqual(x.hour, 23)
    AreEqual(x.minute, 59)
    AreEqual(x.second, 59)
    AreEqual(x.microsecond, 999999)
    #CodePlex Work Item 4865
    y = datetime.datetime(datetime.MAXYEAR, 12, 31, 23, 59, 59, 999999, None)
    AreEqual(x, y)

    #resolution
    #CodePlex Work Item 4866
    x = datetime.datetime.resolution
    AreEqual(x.days, 0)
    AreEqual(x.seconds, 0)
    AreEqual(x.microseconds, 1)

    #equality
    x = datetime.datetime(2005, 3, 22)
    y = x
    Assert(x == y)
    y = datetime.datetime(2005, 3, 23)
    Assert(not (x == y))
    Assert(x == datetime.datetime(2005, 3, 22))

    #inequality
    x = datetime.datetime(2005, 3, 22)
    y = None
    Assert(x != y)
    y = datetime.datetime(2005, 3, 23)
    Assert(x != y)

    #ge/le/gt/lt/eq/ne
    #CodePlex Work Item 4860
    #x_args = [2006, 9, 29, 15, 37, 28, 686000]
    x_args = [2006, 9, 29, 15, 37, 28]
    x = datetime.datetime(*x_args)
    for i in range(len(x_args)):

        y_args = x_args[0:]
        y_args[i] = y_args[i] + 1
        y = datetime.datetime(*y_args)
        x_copy = datetime.datetime(*x_args)

        Assert(y >= x)
        Assert(x <= y)
        Assert(x < y)
        Assert(y > x)
        Assert(not x > y)
        Assert(not x > y)
        Assert(not x == y)
        Assert(x != y)

        Assert(x == x_copy)
        Assert(x_copy >= x)
        Assert(x_copy <= x)

    #date and time
    date = datetime.date(2005, 3, 23)
    time = datetime.time(2, 28, 3, 99)
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    AreEqual(x.date(), date)
    #CodePlex Work Item 4860
    AreEqual(x.time(), time)

    #timetz
    #CodePlex Work Item 4860
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    time = datetime.time(2, 28, 3, 99)
    AreEqual(x.timetz(), time)

    #replace
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    y = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)

    z = x.replace(year=1000)
    AreEqual(y, x)
    AreEqual(z.year, 1000)

    z = x.replace(month=7)
    AreEqual(y, x)
    AreEqual(z.month, 7)

    z = x.replace(day=12)
    AreEqual(y, x)
    AreEqual(z.day, 12)

    z = x.replace(hour=3)
    AreEqual(y, x)
    AreEqual(z.hour, 3)

    z = x.replace(minute=5)
    AreEqual(y, x)
    AreEqual(z.minute, 5)

    z = x.replace(second=25)
    AreEqual(y, x)
    AreEqual(z.second, 25)

    #CodePlex Work Item 4860
    z = x.replace(microsecond=250)
    AreEqual(y, x)
    AreEqual(z.microsecond, 250)

    z = x.replace(year=1000,
                  month=7,
                  day=12,
                  hour=3,
                  minute=5,
                  second=25,
                  microsecond=250)
    AreEqual(y, x)
    AreEqual(z.year, 1000)
    AreEqual(z.month, 7)
    AreEqual(z.day, 12)
    AreEqual(z.hour, 3)
    AreEqual(z.minute, 5)
    AreEqual(z.second, 25)
    #CodePlex Work Item 4860
    AreEqual(z.microsecond, 250)

    #astimezone
    #TODO
    #x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99)
    #x.astimezone(...)

    #utcoffset
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None)
    AreEqual(x.utcoffset(), None)

    #dst
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None)
    AreEqual(x.dst(), None)

    #tzname
    x = datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None)
    AreEqual(x.tzname(), None)

    #timetuple
    AreEqual(
        datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None).timetuple(),
        (2005, 3, 23, 2, 28, 3, 2, 82, -1))

    #utctimetuple
    AreEqual(
        datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None).utctimetuple(),
        (2005, 3, 23, 2, 28, 3, 2, 82, 0))

    #toordinal
    AreEqual(
        datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None).toordinal(), 732028)

    #weekday
    AreEqual(datetime.datetime(2005, 3, 23, 2, 28, 3, 99, None).weekday(), 2)

    #isocalendar
    x = datetime.datetime(2005, 3, 22, 2, 28, 3, 99, None).isocalendar()
    AreEqual(x[0], 2005)
    AreEqual(x[1], 12)
    AreEqual(x[2], 2)

    #isoformat
    x = datetime.datetime(2005, 3, 22, 2, 28, 3, 99, None).isoformat()
    AreEqual(x, '2005-03-22T02:28:03.000099')

    #isoweekday
    AreEqual(
        datetime.datetime(2005, 3, 22, 2, 28, 3, 99, None).isoweekday(), 2)

    #ctime
    AreEqual(
        datetime.datetime(2005, 3, 22, 2, 28, 3, 99, None).ctime(),
        'Tue Mar 22 02:28:03 2005')

    #strftime
    x = datetime.datetime(2005, 3, 22, 2, 28, 3, 99, None)
    AreEqual(x.strftime("%y-%a-%b"), "05-Tue-Mar")
    AreEqual(x.strftime("%Y-%A-%B"), "2005-Tuesday-March")
    AreEqual(x.strftime("%Y%m%d"), '20050322')
    AreEqual(x.strftime("%I:%M:%S"), "02:28:03")
    #Similar to Merlin Work Item 148470
    AreEqual(x.strftime("%H:%M:%S"), "02:28:03")
    #Similar to Merlin Work Item 148470
    if not is_silverlight:
        AreEqual(
            x.strftime(
                "%a %A %b %B %c %d %H %I %j %m %M %p %S %U %w %W %x %X %y %Y %Z %%"
            ),
            "Tue Tuesday Mar March 03/22/05 02:28:03 22 02 02 081 03 28 AM 03 12 2 12 03/22/05 02:28:03 05 2005  %"
        )
예제 #52
0
import pytz
import pytz.tzfile


class tzabbr(datetime.tzinfo):
  """A timezone abbreviation.

  *WARNING*: This is not a tzinfo implementation! Trying to use this as tzinfo
  object will result in failure.  We inherit from datetime.tzinfo so we can get
  through the dateutil checks.
  """
  pass


# A "marker" tzinfo object which is used to signify an unknown timezone.
unknown = datetime.tzinfo()


regions = {"all": {}, "military": {}}
# Create a special alias for the all and military regions
all = regions["all"]
military = regions["military"]


def tzabbr_register(abbr, name, region, zone, dst):
  """Register a new timezone abbreviation in the global registry.

  If another abbreviation with the same name has already been registered it new
  abbreviation will only be registered in region specific dictionary.
  """
  newabbr = tzabbr()
예제 #53
0
def test_time():
    #basic sanity checks
    x = datetime.time(2, 28, 3, 99, datetime.tzinfo())
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)

    x = datetime.time(2, 28, 3, 99, None)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)

    x = datetime.time(2, 28, 3, 99)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 99)

    x = datetime.time(2, 28, 3)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 3)
    AreEqual(x.microsecond, 0)

    x = datetime.time(2, 28)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 28)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)

    x = datetime.time(2)
    AreEqual(x.hour, 2)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)

    x = datetime.time()
    AreEqual(x.hour, 0)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)

    datetime.time(0, 0, 0, 0)  #min
    datetime.time(23, 59, 59, 999999)  #max

    #negative cases
    #CodePlex Work Item 5143
    AssertError(ValueError, datetime.time, -1, 0, 0, 0)
    AssertError(ValueError, datetime.time, 0, -1, 0, 0)
    AssertError(ValueError, datetime.time, 0, 0, -1, 0)
    AssertError(ValueError, datetime.time, 0, 0, 0, -1)
    AssertError(ValueError, datetime.time, -10, -10, -10, -10)

    #CodePlex Work Item 5143
    AssertError(ValueError, datetime.time, 24, 59, 59, 999999)
    AssertError(ValueError, datetime.time, 23, 60, 59, 999999)
    AssertError(ValueError, datetime.time, 23, 59, 60, 999999)
    AssertError(ValueError, datetime.time, 23, 59, 59, 1000000)
    AssertError(ValueError, datetime.time, 24, 60, 60, 1000000)
    AssertError(ValueError, datetime.time, 240, 600, 600, 10000000)

    #min
    x = datetime.time.min
    AreEqual(x.hour, 0)
    AreEqual(x.minute, 0)
    AreEqual(x.second, 0)
    AreEqual(x.microsecond, 0)
    #max
    x = datetime.time.max
    AreEqual(x.hour, 23)
    AreEqual(x.minute, 59)
    AreEqual(x.second, 59)
    AreEqual(x.microsecond, 999999)

    #resolution
    #CodePlex Work Item 5145
    x = datetime.time.resolution
    AreEqual(repr(x), 'datetime.timedelta(0, 0, 1)')

    #equality
    x = datetime.time(1, 2, 33, 444)
    y = x
    Assert(x == y)
    y = datetime.time(1, 2, 33, 445)
    Assert(not (x == y))
    Assert(x == datetime.time(1, 2, 33, 444))

    #inequality
    x = datetime.time(1, 2, 33, 444)
    y = None
    Assert(x != y)
    y = datetime.time(1, 2, 33, 445)
    Assert(x != y)

    #ge
    Assert(datetime.time(1, 2, 33, 444) >= datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 445) >= datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 446) >= datetime.time(1, 2, 33, 444))
    Assert(not (datetime.time(1, 2, 33, 443) >= datetime.time(1, 2, 33, 444)))
    Assert(not (datetime.time(1, 2, 33, 442) >= datetime.time(1, 2, 33, 444)))

    #le
    Assert(datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 445))
    Assert(datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 446))
    Assert(not (datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 443)))
    Assert(not (datetime.time(1, 2, 33, 444) <= datetime.time(1, 2, 33, 442)))

    #gt
    Assert(not (datetime.time(1, 2, 33, 444) > datetime.time(1, 2, 33, 444)))
    Assert(datetime.time(1, 2, 33, 445) > datetime.time(1, 2, 33, 444))
    Assert(datetime.time(1, 2, 33, 446) > datetime.time(1, 2, 33, 444))
    Assert(not (datetime.time(1, 2, 33, 443) > datetime.time(1, 2, 33, 444)))
    Assert(not (datetime.time(1, 2, 33, 442) > datetime.time(1, 2, 33, 444)))

    #lt
    Assert(not (datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 444)))
    Assert(datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 445))
    Assert(datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 446))
    Assert(not (datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 443)))
    Assert(not (datetime.time(1, 2, 33, 444) < datetime.time(1, 2, 33, 442)))

    #hash
    x = datetime.time(1, 2, 33, 444)
    Assert(x.__hash__() != None)

    #bool
    Assert(datetime.time(0, 0, 0, 1))
    #CodePlex Work Item 5139
    Assert(not (datetime.time(0, 0, 0, 0)))

    #replace
    x = datetime.time(1, 2, 33, 444)
    y = datetime.time(1, 2, 33, 444)

    z = x.replace(hour=3)
    AreEqual(y, x)
    AreEqual(z.hour, 3)

    z = x.replace(minute=5)
    AreEqual(y, x)
    AreEqual(z.minute, 5)

    z = x.replace(second=25)
    AreEqual(y, x)
    AreEqual(z.second, 25)

    z = x.replace(microsecond=250)
    AreEqual(y, x)
    AreEqual(z.microsecond, 250)

    z = x.replace(hour=3, minute=5, second=25, microsecond=250)
    AreEqual(y, x)
    AreEqual(z.hour, 3)
    AreEqual(z.minute, 5)
    AreEqual(z.second, 25)
    AreEqual(z.microsecond, 250)

    #isoformat
    #CodePlex Work Item 5146
    x = datetime.time(2, 28, 3, 99).isoformat()
    AreEqual(x, '02:28:03.000099')

    #strftime
    x = datetime.time(13, 28, 3, 99)
    AreEqual(x.strftime("%I:%M:%S"), "01:28:03")
    AreEqual(x.strftime("%H:%M:%S"), "13:28:03")

    #utcoffset
    #CodePlex Work Item 5147
    x = datetime.time(2, 28, 3, 99, None)
    AreEqual(x.utcoffset(), None)

    #dst
    x = datetime.time(2, 28, 3, 99, None)
    AreEqual(x.dst(), None)

    #tzname
    #CodePlex Work Item 5148
    x = datetime.time(2, 28, 3, 99, None)
    AreEqual(x.tzname(), None)
예제 #54
0
 def test_bad_timezone_type(self):
     exc = pytest.raises(TypeError, astimezone, tzinfo())
     assert 'Only timezones from the pytz library are supported' in str(exc.value)
예제 #55
0
def test_datetime_with_tz_not_a_string():
    assert DateTime(tz=datetime.tzinfo())
예제 #56
0
 def test_no_tzinfo(self):
     """no_tzinfo should have known output"""
     dt = datetime.datetime(2000, 1, 1, tzinfo=datetime.tzinfo("MST"))
     self.assertEqual(dt.replace(tzinfo=None), t.no_tzinfo(dt))
     ans = [datetime.datetime(2000, 1, 1)] * 10
     self.assertEqual(ans, t.no_tzinfo([dt] * 10))
예제 #57
0
파일: cast.py 프로젝트: Smattr/mattutils
def main(argv):
    parser = argparse.ArgumentParser(description="turn a music playlist into a servable podcast")
    parser.add_argument("--input", "-i", type=argparse.FileType("r"), required=True, help="playlist to read")
    parser.add_argument("--output", "-o", required=True, help="directory to output to")
    parser.add_argument("--shuffle", action="store_true", help="randomise playlist")
    parser.add_argument("--prefix", required=True, help="webserver root")
    options = parser.parse_args(argv[1:])

    if not os.path.isdir(options.output):
        sys.stderr.write("%s is not a directory\n" % options.output)
        return -1

    for tool in ("ffmpeg", "xmllint"):
        try:
            subprocess.check_call(["which", tool], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except subprocess.CalledProcessError:
            sys.stderr.write("%s not found\n" % tool)
            return -1

    items = []

    start_time = datetime.datetime.now() + datetime.timedelta(hours=-1)

    lines = [x.strip() for x in options.input]
    if options.shuffle:
        random.shuffle(lines)

    for index, line in enumerate(lines):
        guid = digest(line)

        path = os.path.join(options.output, "%s.mp3" % guid)

        sys.stdout.write("Encoding %s...\n" % line)
        p = subprocess.Popen(
            ["ffmpeg", "-y", "-i", line, "-ab", "192k", path], stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        p.communicate()
        if p.returncode != 0:
            sys.stderr.write("Failed\n")
            return -1

        size = os.stat(path).st_size

        duration = int(MP3(path).info.length)

        timestamp = formatdate(
            float((start_time + datetime.timedelta(minutes=index)).strftime("%s")), datetime.tzinfo()
        )

        items.append(
            Item(
                os.path.splitext(os.path.basename(line))[0],
                "%s%s.mp3" % (options.prefix, guid),
                str(size),
                "audio/mpeg",
                timestamp,
                duration="%02d:%02d" % (duration // 60, duration % 60),
            )
        )

    channel = Channel("My Music", options.prefix, "My Music", author=getpass.getuser())
    rss = ET.Element("rss")
    c = channel.attach(rss)
    for i in items:
        i.attach(c)
    et = ET.ElementTree(rss)
    with open(os.path.join(options.output, "feed.xml"), "w") as f:
        et.write(f, encoding="utf-8", xml_declaration=True)

    # Write a Lighttpd conf.
    with open(os.path.join(options.output, "lighttpd.conf"), "w") as f:
        f.write(
            'server.document-root = "%s"\n'
            "server.port = 8000\n"
            'mimetype.assign = (".mp3" => "audio/mpeg")\n' % os.path.abspath(options.output)
        )

    return 0