def test_inverted(): dt1 = pendulum.DateTime(2000, 1, 1) dt2 = pendulum.DateTime(2000, 1, 31) p = pendulum.period(dt2, dt1) assert_datetime(p.start, 2000, 1, 31) assert_datetime(p.end, 2000, 1, 1)
def test_inverted_and_absolute(): dt1 = pendulum.DateTime(2000, 1, 1) dt2 = pendulum.DateTime(2000, 1, 31) p = pendulum.period(dt2, dt1, True) assert_datetime(p.start, 2000, 1, 1) assert_datetime(p.end, 2000, 1, 31)
def test_with_pendulum(): dt1 = pendulum.DateTime(2000, 1, 1) dt2 = pendulum.DateTime(2000, 1, 31) p = pendulum.period(dt1, dt2) assert_datetime(p.start, 2000, 1, 1) assert_datetime(p.end, 2000, 1, 31)
def test_periods_with_same_duration_and_different_dates(): day1 = pendulum.DateTime(2018, 1, 1) day2 = pendulum.DateTime(2018, 1, 2) day3 = pendulum.DateTime(2018, 1, 2) period1 = day2 - day1 period2 = day3 - day2 assert period1 != period2 assert len({period1, period2}) == 2
def test_floor_divide(): dt1 = pendulum.DateTime(2016, 8, 7, 12, 34, 56) dt2 = dt1.add(days=2, seconds=34) it = pendulum.period(dt1, dt2) mul = it // 2 assert isinstance(mul, pendulum.Duration) assert_duration(mul, 0, 0, 0, 1, 0, 0, 17) dt1 = pendulum.DateTime(2016, 8, 7, 12, 34, 56) dt2 = dt1.add(days=2, seconds=35) it = pendulum.period(dt1, dt2) mul = it // 3 assert isinstance(mul, pendulum.Duration) assert_duration(mul, 0, 0, 0, 0, 16, 0, 11)
def test_multiply(): dt1 = pendulum.DateTime(2016, 8, 7, 12, 34, 56) dt2 = dt1.add(days=6, seconds=34) it = pendulum.period(dt1, dt2) mul = it * 2 assert isinstance(mul, pendulum.Duration) assert_duration(mul, 0, 0, 1, 5, 0, 1, 8) dt1 = pendulum.DateTime(2016, 8, 7, 12, 34, 56) dt2 = dt1.add(days=6, seconds=34) it = pendulum.period(dt1, dt2) mul = it * 2 assert isinstance(mul, pendulum.Duration) assert_duration(mul, 0, 0, 1, 5, 0, 1, 8)
async def birthday(self, ctx: context.Context, *, person: converters.UserConverter = None) -> None: """ Displays the birthday of you, or the member provided. `person`: The person to display the birthday of. Can be their name, id or mention. If this argument is not passed the command will display your birthday. """ if person is None: person = ctx.author user_config = self.bot.user_manager.get_user_config(user_id=person.id) if user_config.birthday == pendulum.DateTime( 2020, 1, 1, 0, 0, 0, tzinfo=pendulum.timezone('UTC')): raise exceptions.ArgumentError( f'`{person}` has not set their birthday.') if user_config.birthday_private and ctx.author.id != person.id: raise exceptions.ArgumentError( f'`{person}` has their birthday set to be private.') embed = discord.Embed( description=f'`{person.name}`**\'s birthday information:**\n\n' f'`Birthday:` {self.bot.utils.format_date(datetime=user_config.birthday)}\n' f'`Next birthday:` In {self.bot.utils.format_difference(datetime=user_config.next_birthday.subtract(days=1), suppress=[])}\n' f'`Age:` {user_config.age}\n', colour=user_config.colour) await ctx.send(embed=embed)
def local_date_to_time(date, none=False): if none and date is None: return None date = to_date(date) ptime = p.DateTime(year=date.year, month=date.month, day=date.day, tzinfo=p.tz.get_local_timezone()).in_timezone(pytz.UTC) return dt.datetime(*ptime.timetuple()[:6], tzinfo=pytz.UTC)
def local_date_to_time(date): date = to_date(date) ptime = p.DateTime(year=date.year, month=date.month, day=date.day, tzinfo=p.tz.get_local_timezone()).in_timezone( dt.timezone.utc) return dt.datetime(*ptime.timetuple()[:6], tzinfo=dt.timezone.utc)
def test_timedelta_behavior(): dt1 = pendulum.DateTime(2000, 11, 20, 1) dt2 = pendulum.DateTime(2000, 11, 25, 2) dt3 = pendulum.DateTime(2016, 11, 5, 3) p1 = pendulum.period(dt1, dt3) p2 = pendulum.period(dt2, dt3) it1 = p1.as_timedelta() it2 = p2.as_timedelta() assert it1.total_seconds() == p1.total_seconds() assert it2.total_seconds() == p2.total_seconds() assert it1.days == p1.days assert it2.days == p2.days assert it1.seconds == p1.seconds assert it2.seconds == p2.seconds assert it1.microseconds == p1.microseconds assert it2.microseconds == p2.microseconds
def cleanse_time(time_): if isinstance(time_, int): now = pendulum.now() date = pendulum.DateTime( now.year, now.month, now.day) + pendulum.duration(seconds=time_) time_ = date.strftime('%H:%M:%S') if isinstance(time_, str): pendulum.DateTime.strptime(time_, '%H:%M:%S') return time_
def test_download_inexistent_day(self, client, tmp_path): date = pendulum.DateTime(2019, 9, 27) wellness = Wellness(date) with client: client.session.get = Mock(return_value=get_mocked_response(404), func_name="client.session.get()") wellness.download(client, tmp_path) expected_downloaded_file_path = wellness.get_export_filepath( tmp_path) assert not expected_downloaded_file_path.exists() assert (Path(tmp_path) / ".not_found").exists() assert (expected_downloaded_file_path.name in (Path(tmp_path) / ".not_found").read_text())
def test_accuracy(): dt1 = pendulum.DateTime(2000, 11, 20) dt2 = pendulum.DateTime(2000, 11, 25) dt3 = pendulum.DateTime(2016, 11, 5) p1 = pendulum.period(dt1, dt3) p2 = pendulum.period(dt2, dt3) assert p1.years == 15 assert p1.in_years() == 15 assert p1.months == 11 assert p1.in_months() == 191 assert p1.days == 5829 assert p1.remaining_days == 2 assert p1.in_days() == 5829 assert p2.years == 15 assert p2.in_years() == 15 assert p2.months == 11 assert p2.in_months() == 191 assert p2.days == 5824 assert p2.remaining_days == 4 assert p2.in_days() == 5824
def test_download(self, client_wellness, tmp_path): date = pendulum.DateTime(2019, 9, 27) wellness = Wellness(date) with client_wellness: wellness.download(client_wellness, tmp_path) client_wellness.get_wellness.assert_called_once() client_wellness.get_wellness.assert_called_with(date) expected_downloaded_file_path = wellness.get_export_filepath( tmp_path) assert expected_downloaded_file_path.exists() assert not (Path(tmp_path) / ".not_found").exists() zipped_file = RESPONSE_EXAMPLES_PATH / "example_original_with_fit.zip" assert (expected_downloaded_file_path.read_bytes() == zipped_file.read_bytes())
def scan(self): # important to process log-rotated logfiles in order, so timestamps are preserved for entry in sorted(os.listdir(self._config.logdir)): automountLogRE = re.compile(r"""^automount-(\d\d\d\d)(\d\d)(\d\d).gz$""") m = automountLogRE.match(entry) if m: logpath = os.path.join(self._config.logdir, entry) logfile_year = int(m.group(1)) logfile_month = int(m.group(2)) logfile_day = int(m.group(3)) logfile_dt = pendulum.DateTime(logfile_year, logfile_month, logfile_day, tzinfo=pendulum.now().timezone) self._collate_if_pending(logpath, logfile_dt, compressed=True) # finally look at the uncompressed logfile logpath = os.path.join(self._config.logdir, 'automount') if os.path.exists(logpath): logfile_dt = pendulum.from_timestamp(os.path.getmtime(logpath), tz=pendulum.now().timezone_name) self._collate_if_pending(logpath, logfile_dt, compressed=False) self._collator.finalize()
async def birthday_upcoming(self, ctx: context.Context) -> None: """ Displays a list of upcoming birthdays within the server. """ configs = sorted(self.bot.user_manager.configs.items(), key=lambda user_config: user_config[1].birthday) birthdays = {} for user_id, config in configs: member = ctx.guild.get_member(user_id) if not member: continue if config.birthday_private or config.birthday == pendulum.DateTime( 2020, 1, 1, 0, 0, 0, tzinfo=pendulum.timezone('UTC')): continue birthdays[member] = config if not birthdays: raise exceptions.ArgumentError( 'There are no users who have set their birthday in this server, or everyone has them private.' ) birthdays_format = "\n\n".join( f'__**`{person.name}`\'s birthday:**__\n' f'`Birthday:` {self.bot.utils.format_date(datetime=user_config.birthday)}\n' f'`Next birthday:` In {self.bot.utils.format_difference(datetime=user_config.next_birthday.subtract(days=1), suppress=[])}\n' f'`Current age:` {user_config.age}' for person, user_config in list(birthdays.items())[:5]) embed = discord.Embed( description=f'**Upcoming birthdays:**\n\n{birthdays_format}', colour=ctx.colour) await ctx.send(embed=embed)
async def historyEvents(self) -> None: # Get tomorrow's date so once midnight hits, the correct date can be checked tomorrowDate = pendulum.now().add(days=1) midnight: pendulum.DateTime = pendulum.DateTime( year=tomorrowDate.year, month=tomorrowDate.month, day=tomorrowDate.day, hour=23, minute=59, tzinfo=tomorrowDate.tzinfo) await asyncio.sleep(tomorrowDate.diff(midnight).in_seconds() + 120) tomorrowEvent = [ event for event in self.historyEventsTable if tomorrowDate.strftime("%d/%m") in event[1] ] if len(tomorrowEvent) == 1: tomorrowDateString = pendulum.from_format( tomorrowEvent[0][1], "D/MM/YYYY").format("Do of MMMM YYYY") historyEmbed = Embed( title=f"Today on the {tomorrowDateString}, this happened:", description=tomorrowEvent[0][0], colour=self.colour) for guild in self.bot.guilds: await self.sendEmbed(guild, historyEmbed)
def __init__(self) -> None: self.colour = discord.Colour.gold() self.blacklisted = False self.blacklisted_reason = 'None' self.timezone = pendulum.timezone('UTC') self.timezone_private = False self.xp = 0 self.coins = 0 self.level_up_notifications = False self.daily_collected = pendulum.now(tz='UTC') self.weekly_collected = pendulum.now(tz='UTC') self.monthly_collected = pendulum.now(tz='UTC') self.daily_streak = 0 self.weekly_streak = 0 self.monthly_streak = 0 self.created_at = pendulum.now(tz='UTC') self.birthday = pendulum.DateTime(2020, 1, 1, 0, 0, 0, tzinfo=pendulum.timezone('UTC')) self.birthday_private = False self.reminders = [] self.requires_db_update = []
def test_periods_with_same_dates(): period1 = pendulum.DateTime(2018, 1, 2) - pendulum.DateTime(2018, 1, 1) period2 = pendulum.DateTime(2018, 1, 2) - pendulum.DateTime(2018, 1, 1) assert period1 == period2 assert len({period1, period2}) == 1
def test_instantiation(self, tmp_path): date = pendulum.DateTime(2019, 9, 27) wellness = Wellness(date) assert wellness.base_filename == "2019-09-27.zip" assert wellness.get_export_filepath( tmp_path) == tmp_path / "2019-09-27.zip"
status="up", # NOTE: Shows different ways to set the date type objects last_status_change="2019-06-01 12:22", last_clear=1496498400, physical=INTERFACE_PHYSICAL_ARGS["standard2"], addresses=INTERFACE_IP_ARGS["ipv6_only"], counters=INTERFACE_COUNTERS_ARGS["normal"], ), "portchannel_disabled": dict( name="Po200", description="L3 PEERLINK", enabled=False, status_up=False, status="disabled", last_status_change=pendulum.DateTime(2019, 2, 25, 17, 54, 42, 464872), number_status_changes=2, forwarding_model="routed", physical=INTERFACE_PHYSICAL_ARGS["standard2"], optical=INTERFACE_OPTICAL_ARGS["green"], addresses=INTERFACE_IP_ARGS["all_ips"], instance="default", counters=INTERFACE_COUNTERS_ARGS["normal"], members=["Ethernet52", "Ethernet51"], last_clear=None, update_interval=300.0, ), "l3_vlan": dict(name="Vl177"), "l2_eth_optical": dict(name="Ethernet52"),
def time_to_local_date(time): time = to_time(time) ptime = p.DateTime(*time.timetuple()[:6], tzinfo=pytz.UTC).in_timezone(p.tz.get_local_timezone()) return dt.date(year=ptime.year, month=ptime.month, day=ptime.day)
datetime_now = datetime.datetime.now(pytz.timezone('MST')) # Mongo drops portion of microsecond, field truncates automatically for consistency datetime_now = datetime_now.replace( microsecond=int(math.floor(datetime_now.microsecond / 1000) * 1000)) pendulum_now = pendulum.instance(datetime_now) pendulum_interval = pendulum.duration(minutes=5) @pytest.mark.parametrize( 'field_name,dt,expected_raw', [('Incident Closed', pendulum_now, DatetimeField.format_datetime(pendulum_now)), ('Date Field', pendulum_now, DatetimeField.format_datetime( pendulum.DateTime(pendulum_now.year, pendulum_now.month, pendulum_now.day))), ('Time Field', pendulum_now, DatetimeField.format_datetime(pendulum_now)), ('Incident Duration', pendulum_interval, pendulum_interval.in_seconds() * 1000)]) def test_raw_serialization(mock_record, field_name, dt, expected_raw): """Test that datetime field values are appropriately serialized to raw""" mock_record[field_name] = dt field_id = mock_record.app.get_field_definition_by_name(field_name)['id'] assert mock_record._raw['values'][field_id] == expected_raw @pytest.mark.parametrize( 'valid_date_obj', [datetime_now, datetime_now.date(), pendulum_now, pendulum_now.date()])