def test_initialize_with_naive_datetime_with_string_timezone(self): dt = datetime(2015, 1, 1) tz_str = 'US/Pacific' tz = pytz.timezone(tz_str) do = delorean.Delorean(dt, timezone=tz_str) tz = tz.localize(datetime(2015, 1, 1)).tzinfo dt = tz.localize(dt) self.assertEqual(do.datetime, dt) self.assertEqual(do.timezone, tz)
def test_localize_datetime(self): dt = datetime.utcnow() tz = pytz.timezone("US/Pacific") dt = tz.localize(dt) d = delorean.Delorean(dt) d2 = d.shift('US/Pacific') self.assertEqual(d.timezone.tzname(None), "US/Pacific") self.assertEqual(d.datetime, dt) self.assertEqual(d.datetime, d2.datetime)
def test_range_with_start(self): dates1 = [] for do in delorean.stops(delorean.DAILY, count=5, start=datetime.utcnow()): do.truncate('minute') dates1.append(do) do = delorean.Delorean().truncate('minute') dates2 = [] for x in range(5): dates2.append(do.next_day(x)) self.assertEqual(dates1, dates2)
def test_initialize_without_datetime_with_string_timezone(self, mock_datetime_timezone): tz_str = 'US/Pacific' tz = pytz.timezone(tz_str) dt = tz.localize(datetime(2015, 1, 1)) tz = dt.tzinfo mock_datetime_timezone.return_value = dt do = delorean.Delorean(timezone=tz_str) self.assertEqual(do.datetime, dt) self.assertEqual(do.timezone, tz)
def test_initialize_with_tzinfo_generic(self): self.aware_dt_generic = datetime(2013, 1, 3, 4, 31, 14, 148540, tzinfo=generic_utc) do = delorean.Delorean(datetime=self.aware_dt_generic) self.assertTrue(type(do) is delorean.Delorean)
def test_initialize_with_tzinfo_pytz(self): self.aware_dt_pytz = datetime(2013, 1, 3, 4, 31, 14, 148540, tzinfo=utc) do = delorean.Delorean(datetime=self.aware_dt_pytz) self.assertTrue(type(do) is delorean.Delorean)
def test_initialize_with_tzinfo_pytz(self): aware_dt_pytz = datetime(2013, 1, 3, 4, 31, 14, 148540, tzinfo=pytz.utc) do = delorean.Delorean(datetime=aware_dt_pytz) self.assertTrue(isinstance(do, delorean.Delorean))
def test_initialize_with_tzinfo_generic(self): aware_dt_generic = datetime(2013, 1, 3, 4, 31, 14, 148540, tzinfo=generic_utc) do = delorean.Delorean(datetime=aware_dt_generic) self.assertTrue(isinstance(do, delorean.Delorean))
def test_range_with_interval(self): dates1 = [] for do in delorean.stops(delorean.DAILY, interval=2, count=3, start=datetime.utcnow()): do.truncate('minute') dates1.append(do) do = delorean.Delorean().truncate('minute') dates2 = [] for x in range(6): if (x % 2) == 0: dates2.append(do.next_day(x)) self.assertEqual(dates1, dates2)
def test_range_with_start_and_stop(self): dates1 = [] tomorrow = datetime.utcnow() + timedelta(days=1) for do in delorean.stops(delorean.DAILY, start=datetime.utcnow(), stop=tomorrow): do.truncate('minute') dates1.append(do) do = delorean.Delorean().truncate('minute') dates2 = [] for x in range(2): dates2.append(do.next_day(x)) self.assertEqual(dates1, dates2)
def get_date_range(start: date = None, back: int = 1, forward: int = 12) -> (date, date): """ Returns a date range of "back" months before and "forward" months after given date, or today. """ base = delorean.Delorean(start, timezone=settings.TIME_ZONE) begin = base.last_month(back).date.replace(day=1) end = base.next_month(forward).date.replace(day=1) return begin, end
def test_initialize_with_naive_datetime_with_dateutil_timezone(self): dt = datetime(2015, 1, 1) tz = tzoffset(None, -22500) do = delorean.Delorean(dt, timezone=tz) utcoffset = tz.utcoffset(None) total_seconds = ( (utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10 ** 6) / 10 ** 6) tz = pytz.FixedOffset(total_seconds / 60) dt = tz.localize(dt) self.assertEqual(do.datetime, dt) self.assertEqual(do.timezone, tz)
def parse_datetime(text, loader_context): if not isinstance(text, str): return text try: return delorean.parse( text.strip(), timezone=loader_context.get('timezone', 'UTC'), dayfirst=loader_context.get('dayfirst', False), yearfirst=loader_context.get('yearfirst', True)).shift('UTC') except ValueError: return delorean.Delorean( dateparser.parse(text), timezone=loader_context.get('timezone', 'UTC'))
async def timezone_convert(self, ctx, time, from_loc, to_loc): """Convert time from location to location. !tz convert "2017-05-14 9:00" EST Sydney !tz convert "2017-05-14 9:00" "Hong Kong" London """ if from_loc.upper() in TZ_ABBREV: from_loc = TZ_ABBREV[from_loc.upper()] if to_loc.upper() in TZ_ABBREV: to_loc = TZ_ABBREV[to_loc.upper()] from_tz = self.get_timezone(from_loc) to_tz = self.get_timezone(to_loc) from_time = delorean.parse(time) orig_time = delorean.Delorean(datetime=from_time.naive, timezone=from_tz["timeZoneId"]) converted_time = delorean.Delorean(datetime=from_time.naive, timezone=from_tz["timeZoneId"]) converted_time.shift(to_tz["timeZoneId"]) dt_fmt = "%A, %B %d, %Y at %H:%M:%S" msg = ("{} \n" "for {} \n" "is \n" "{} \n" "for {}.").format( orig_time.datetime.strftime(dt_fmt), "{} ({})".format(from_tz["timeZoneId"], from_tz["timeZoneName"]), converted_time.datetime.strftime(dt_fmt), "{} ({})".format(to_tz["timeZoneId"], to_tz["timeZoneName"])) await self.bot.say(msg)
def get_time_range(start=None, back=1, forward=6): """ From a starting date from back and forward by given amount and return start of both months as dates :param start: datetime.date :param back: int :param forward: int :return: (datetime.date, datetime.date) """ base = delorean.Delorean(start) start = base.last_month(back).date.replace(day=1) end = base.next_month(forward).date.replace(day=1) return start, end
def test_initialize_without_datetime_with_dateutil_timezone(self, mock_datetime_timezone): tz = tzoffset(None, -22500) dt = datetime(2015, 1, 1, tzinfo=tz) utcoffset = tz.utcoffset(None) total_seconds = ( (utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10 ** 6) / 10 ** 6) tz = pytz.FixedOffset(total_seconds / 60) dt = tz.normalize(dt) mock_datetime_timezone.return_value = dt do = delorean.Delorean(timezone=tz) self.assertEqual(do.datetime, dt) self.assertEqual(do.timezone, tz)
def get_book_info(base_page=free_learning_page): epoch = delorean.Delorean(datetime.utcnow(), timezone="UTC").truncate('day').epoch image_filename = '.freelearning_cache/book_image_' + str(epoch) + '.jpg' http = httplib2.Http('.freelearning_cache') try: book_info_response, book_info_html = http.request(base_page) book_info_soup = BeautifulSoup(book_info_html, "lxml") if book_info_response.fromcache is False: image_url = 'http:' + book_info_soup.find( "img", {"class": "bookimage"})['src'] urllib.urlretrieve( image_url, image_filename) # why can't httplib2 fetch this? # 1. Value types title = re.sub( '\n', '', re.sub( '\t', '', book_info_soup.find("div", { "class": "dotd-title" }).find("h2").text)) description_haystack = book_info_soup.find( "div", { "class": "dotd-main-book-summary" }).findAll("div") description = '' for description_needle in description_haystack: if not description_needle.has_attr("class"): description += html2text.html2text(description_needle.text) book_info_dict = dict(error=False, title=title, image=image_filename, description=re.sub("\n", ' ', description)) return book_info_dict except httplib2.ServerNotFoundError: return dict(error=True, title="Error", image="", description="Unable to open URL: " + base_page)
def test_replace(self): do = delorean.Delorean(datetime(2015, 1, 1), timezone='US/Pacific') dt = do.datetime # Check if parts are okay self.assertEqual(do.replace(hour=8).datetime.hour, 8) self.assertEqual(do.replace(minute=23).datetime.minute, 23) self.assertEqual(do.replace(second=45).datetime.second, 45) # Asserts on datetimes self.assertEqual(do.replace(hour=8).datetime, dt.replace(hour=8)) self.assertEqual(do.replace(minute=38).datetime, dt.replace(minute=38)) self.assertEqual(do.replace(second=48).datetime, dt.replace(second=48)) # Test that the timezone does not change self.assertEqual(do.replace(second=45).timezone, do.timezone) # Test the datetime eight_hours_late = dt + timedelta(hours=8) self.assertEqual(do.replace(hour=8).datetime, eight_hours_late)
def write_to_gdoc(docID, message, service): test = delorean.Delorean() t = "US/Central" #user.timezone pytz.all_timezones date_time = to_human_readable(test, t) requests = [{ 'insertText': { 'location': { 'index': 1 }, 'text': message + "\n\n" } }, { 'insertText': { 'location': { 'index': 1 }, 'text': date_time + "\n\n" } }] service.documents().batchUpdate(documentId=docID, body={ 'requests': requests }).execute()
def _delorean(): dt = datetime.fromtimestamp(TIME) return delorean.Delorean(datetime=dt, timezone=pytz.FixedOffset( get_local_utc_offset()))
def test_equal(self): d1 = delorean.Delorean() d2 = deepcopy(d1) self.assertEqual(d1, d2) self.assertFalse(d1 != d2, 'Overloaded __ne__ is not correct')
def test_not_equal(self): d = delorean.Delorean() self.assertNotEqual(d, None)
def test_gt(self): dt1 = self.do dt2 = delorean.Delorean() self.assertTrue(dt2 > dt1)
def test_lt(self): dt1 = self.do dt2 = delorean.Delorean() self.assertTrue(dt1 < dt2)
def test_datetime_localization(self): dt1 = self.do.datetime dt2 = delorean.Delorean(dt1).datetime self.assertEqual(dt1, dt2)
def test_delorean_with_datetime(self): dt = datetime.utcnow() d = delorean.Delorean(datetime=dt, timezone=UTC) dt = utc.localize(dt) self.assertEqual(dt, d._dt) self.assertEqual(UTC, d._tz)
def setUp(self): self.naive_dt = datetime(2013, 1, 3, 4, 31, 14, 148540) self.do = delorean.Delorean(datetime=self.naive_dt, timezone="UTC")
def test_datetime_timezone(self): do = delorean.Delorean(timezone="US/Eastern") do.truncate("minute") dt1 = delorean.datetime_timezone(tz="US/Eastern") self.assertEqual(dt1.replace(second=0, microsecond=0), do.datetime)
def test_datetime_timezone_default(self): do = delorean.Delorean() do.truncate('minute') dt1 = delorean.datetime_timezone(UTC) self.assertEqual(dt1.replace(second=0, microsecond=0), do.datetime)
def test_timezone(self): utc = timezone('UTC') do_timezone = delorean.Delorean().timezone() self.assertEqual(utc, do_timezone)