示例#1
0
def to_timestamp(dt_str=None, tz_str=None):
    t_re = r'[\d]{4}\-(\d|[0-1]\d)\-(\d|[0-2]\d|3[0-1])\s+?(2[0-4]|[0-1]\d|\d)[\:]([0-5]\d|\d)[\:]([0-5]\d|\d)'
    utc_re = r'UTC([\-|\+])((2[0-4]|[0-1]\d|\d):([0-5]\d|\d))'
    if dt_str is not None:
        if re.match(t_re,dt_str):
            if tz_str is not None:
                if re.match(utc_re,tz_str):
                    utc_list = re.match(utc_re,tz_str).groups()
                    if len(utc_list) == 4:
                        hours_num = int(utc_list[0]+utc_list[2])
                        t = datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')
                        utc_time = timezone(timedelta(hours=hours_num))
                        ts = t.replace(tzinfo=utc_time)
                        ts = datetime.timestamp(ts)
                        print(ts)

                else:
                    print('UTC格式不正确')
            else:
                t = datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')
                utc_time = timezone(timedelta(hours=8))
                ts = t.replace(tzinfo=utc_time)
                ts = datetime.timestamp(ts)
                print(ts)
        else:
            print('时间格式不正确!')
    else:
        print('缺少必要的参数,请确保传入了日期与时间值')
示例#2
0
 def test_userObjectCreatesCorrectly(self):
     userToTest = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)))
     self.assertEqual(userToTest.username, 'test')
     self.assertEqual(userToTest.authToken, '123456-012e1')
     self.assertEqual(userToTest.secretToken, '123h4123asdhh123')
     self.assertEqual(userToTest.timeZone, timezone(timedelta(hours = 5, minutes = 30)))
     self.assertIsNone(userToTest.userId)
    def test_messageIsSentCorrectlyWhenOver140Chars(self, sendReplyPatch, usernameMethod, urlLengthPatch):
        sendReplyPatch.side_effect = [1234, 1235, 1236]
        urlLengthPatch.return_value = (23,23)
        usernameMethod.return_value = "example"

        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) 
        replyToSend = Reply(1, 
                "@example an example message that is just way too long to be kept inside a single tweet. Therefore it will be broken down into lots of little messages each having the example username on top of it. Sounds cool? Keep going! I'd really like to make this message about 3 tweets long so that I can make sure that the module is working properly. Like really well.",
                d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)

        user = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)))
        mockUserDataStrategy = Mock()
        mockUserDataStrategyAttrs = {"getUserById.return_value": user }
        mockUserDataStrategy.configure_mock(**mockUserDataStrategyAttrs)
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"getReplyByReplyId.side_effect": [copy.deepcopy(replyToSend), copy.deepcopy(replyToSend)]}
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        DataConfig.ReplyDataStrategy = mockReplyDataStrategy
        DataConfig.UserDataStrategy = mockUserDataStrategy
        self.assertEqual(MessageSender.sendMessage(1, ""), {"result": "success", "value": {"tweets": [1234, 1235, 1236]}})
        usernameMethod.assert_called_once_with(134953292, 1, mockUserDataStrategy)
        t1 = "@example an example message that is just way too long to be kept inside a single tweet. Therefore it will be broken down into lots of little"
        t2 = "@example messages each having the example username on top of it. Sounds cool? Keep going! I'd really like to make this message about 3"
        t3 = "@example tweets long so that I can make sure that the module is working properly. Like really well."
        sendReplyPatch.assert_any_call(t1, 134953292, 1, mockUserDataStrategy)
        sendReplyPatch.assert_any_call(t2, 1234, 1, mockUserDataStrategy)
        sendReplyPatch.assert_any_call(t3, 1235, 1, mockUserDataStrategy)
        self.assertTrue(mockReplyDataStrategy.updateReply.called)
示例#4
0
    def test_scheduleUpdatedCorrectly(self):
        expectedSchedule = '0 7 1 1 * /bin/sh /replylater/src/core/runmessage.sh --id=1 --data=sqllite # 1'
        tz = timezone(timedelta(hours=5, minutes=30))
        d = datetime(year=2022, month=1, day=1, hour=12, minute=30, tzinfo=tz)
        Scheduler.scheduleReply(1, d)
        c = CronTab(user=True)
        iter = c.find_comment('1')
        jobs = [i for i in iter]
        self.assertEqual(len(jobs), 1)
        self.assertEqual(str(jobs[0]), expectedSchedule)

        d = datetime(year=2022, month=2, day=1, hour=12, minute=30, tzinfo=tz)
        expectedSchedule = '0 7 1 2 * /bin/sh /replylater/src/core/runmessage.sh --id=1 --data=sqllite # 1'
        Scheduler.updateReply(1, d)
        c = CronTab(user=True)
        iter = c.find_comment('1')
        jobs = [i for i in iter]
        self.assertEqual(len(jobs), 1)
        self.assertEqual(str(jobs[0]), expectedSchedule)

        tz = timezone(timedelta(hours=4, minutes=0))
        d = datetime(year=2022, month=2, day=1, hour=12, minute=30, tzinfo=tz)
        expectedSchedule = '30 8 1 2 * /bin/sh /replylater/src/core/runmessage.sh --id=1 --data=sqllite # 1'
        Scheduler.updateReply(1, d)
        c = CronTab(user=True)
        iter = c.find_comment('1')
        jobs = [i for i in iter]
        self.assertEqual(len(jobs), 1)
        self.assertEqual(str(jobs[0]), expectedSchedule)
示例#5
0
 def setUp(self):
     self.client = Client()
     self.questionnaire = Questionnaire.objects.create(intro='Hello, this is a question',label='This is the descriptionish')
     startdate = datetime.now(timezone(timedelta(hours=2)))
     enddate = datetime.now(timezone(timedelta(hours=2)))
     self.round = RoundDetail.objects.create(name='test round',questionnaire=self.questionnaire,startingDate=startdate,endingDate=enddate, description='Hey there, we have a round')
     self.user = User.objects.create_user('*****@*****.**', 'bob')
 def test_userCanBeUpdated(self):
     userToTest = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)))
     self.assertEqual(UserCRUD.saveUser(userToTest, UserDataStrategy), {"result": "success", "value": 1, "updated": False})
     userToTest = User('test', '123456-012e1asda', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)), userId = 1)
     self.assertEqual(UserCRUD.updateUser(userToTest, UserDataStrategy), {"result": "success"})
     userToTest = UserCRUD.getUserById(1, UserDataStrategy)
     self.assertEqual(userToTest.authToken, '123456-012e1asda')
def convertReplyRowToObject(result):
    timeZoneInformation = [result["timeZoneDifferenceDays"], result["timeZoneDifferenceSeconds"]]
    if timeZoneInformation[0] == -1:
        tz = timezone(timedelta(seconds=result["timeZoneDifferenceSeconds"] * -1))
    else:
        tz = timezone(timedelta(seconds=result["timeZoneDifferenceSeconds"]))

    t = time.strptime(result["scheduledTime"].split("+")[0].split(".")[0], "%Y-%m-%d %H:%M:%S")
    if len(result["scheduledTime"].split("+")[0].split(".")) == 1:
        microsecond = 0
    else:
        microsecond = int(result["scheduledTime"].split("+")[0].split(".")[1])

    d = datetime(
        t.tm_year,
        t.tm_mon,
        t.tm_mday,
        hour=t.tm_hour,
        minute=t.tm_min,
        second=t.tm_sec,
        microsecond=microsecond,
        tzinfo=tz,
    )
    replyToReturn = Reply(
        result["userId"], result["message"], d, tz, result["tweetId"], result["sentStatus"], replyId=result["ROWID"]
    )
    return replyToReturn
示例#8
0
 async def time(self, ctx, timezone=None):
     """Prints out the current guild time, HH:MM:SS format. If provided, timezone should be a timezone """ \
         """shorthand such as EST or of the format [+/-]hhmm, for example +0500."""
     if not timezone:
         tz = self.bot.get_timezone(ctx)
     else:
         if utils.tz_map.get(timezone):
             tz = dt.timezone(dt.timedelta(hours=utils.tz_map[timezone]), timezone)
         else:
             try:
                 timezone = float(timezone)
             except ValueError:
                 await ctx.send("Invalid timezone format")
                 return
             if -24 < timezone < 24:
                 name = f"{int(timezone * 100):+05}"
                 tz = dt.timezone(dt.timedelta(hours=timezone), name)
             elif -2360 < timezone <= 2360:
                 timezone = timezone / 100
                 hours, minutes = str(timezone).split(".")
                 if len(minutes) == 1:
                     minutes = str(int(minutes) * 10)
                 hours = int(hours)
                 minutes = int(minutes)
                 name = f"{int(timezone * 100):+05}"
                 tz = dt.timezone(dt.timedelta(hours=hours, minutes=minutes), name)
             else:
                 await ctx.send("Offset must be between -24 hours and 24 hours, exclusive.")
                 return
     await ctx.send(
         f"It's time to get a watch. {dt.datetime.now(tz=tz).strftime('%H:%M:%S')} {tz.tzname(None)}"
     )
示例#9
0
    def cmd_time(self, player, msg, channel):
        """Responds with the current time."""
        tz_offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
        tz_offset = tz_offset // 60 // 60 * -1
        tz = datetime.timezone(offset=datetime.timedelta(hours=tz_offset))
        now = datetime.datetime.now(tz)

        if len(msg) > 1:

            try:
                tz_offset = int(msg[1])
                tz = datetime.timezone(offset=datetime.timedelta(hours=tz_offset))
                now = datetime.datetime.now(tz)
            except ValueError:
                self.after_command(lambda:
                channel.reply("Unintelligible time zone offset."))
                return

        if tz_offset > 0:
            self.after_command(lambda:
            channel.reply("The current time is: ^6{} UTC+{}"
                .format(now.strftime(TIME_FORMAT), tz_offset)))
        elif tz_offset < 0:
            self.after_command(lambda:
                channel.reply("The current time is: ^6{} UTC{}"
                .format(now.strftime(TIME_FORMAT), tz_offset)))
        else:
            self.after_command(lambda:
            channel.reply("The current time is: ^6{} UTC"
                .format(now.strftime(TIME_FORMAT))))
示例#10
0
def analyze(page):
    try:
        statuses=page['statuses']
        count=page['count']
        TimeUpper=statuses[1]["timeBefore"]
        TimeLower=statuses[count-1]["timeBefore"]
        TimeUpper = TimeUpper.replace('-', '')
        TimeUpper=TimeUpper.split()[0]
        TimeLower = TimeLower.replace('-', '')
        TimeLower = TimeLower.split()[0]
        if len(TimeLower) ==4:
            TimeLower='2018'+TimeLower
        if len(TimeUpper) == 4:
            TimeUpper = '2018' + TimeUpper
        special=str('今天')
        special_2=str('分钟前')
        if TimeUpper==special or TimeUpper==special_2 :
            utc_d = datetime.utcnow().replace(tzinfo=timezone.utc)
            utc_dt = utc_d.astimezone(timezone(timedelta(hours=8)))
            TimeUpper = utc_dt.strftime("%Y-%m-%d")
            TimeUpper = TimeUpper.replace('-', '')
        if TimeLower == special or TimeLower == special_2:
            utc_d = datetime.utcnow().replace(tzinfo=timezone.utc)
            utc_dt = utc_d.astimezone(timezone(timedelta(hours=8)))
            TimeLower = utc_dt.strftime("%Y-%m-%d")
            TimeLower = TimeLower.replace('-', '')
        return TimeLower, TimeUpper,statuses
    except Exception as e:
        pass
示例#11
0
 def test_replyObjectSavesCorrectly(self, scheduleReplyPatch):
     d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToSave = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
     mockReplyDataStrategy = Mock()
     mockReplyDataStrategyAttrs = {"saveReply.return_value": 1}
     mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
     self.assertEqual(ReplyCRUD.saveReply(replyToSave, mockReplyDataStrategy), {"result": "success", "value": 1})
     scheduleReplyPatch.assert_called_once_with(1, d)
示例#12
0
 def test_replyCanBeRetrievedById(self):
     d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToRetrieve = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
     mockReplyDataStrategy = Mock()
     mockReplyDataStrategyAttrs = {"getReplyByReplyId.return_value": replyToRetrieve}
     mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
     self.assertEqual(ReplyCRUD.getReplyByReplyId(1, mockReplyDataStrategy), replyToRetrieve)
     self.assertTrue(mockReplyDataStrategy.getReplyByReplyId.called)
示例#13
0
 def test_messageIsBrokenDownCorrectlyBeforeSending(self):
     user = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)))
     mockUserDataStrategy = Mock()
     mockUserDataStrategyAttrs = {"getUserById.return_value": user }
     mockUserDataStrategy.configure_mock(**mockUserDataStrategyAttrs)
     d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToSend = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
     self.assertEqual(MessageBreaker.breakMessage(replyToSend.message, replyToSend.tweetId, 1, mockUserDataStrategy), ["@example an example message"])
 def test_replyCanBeCancelled(self, removeReplyPatch, scheduleReplyPatch, updateReplyPatch):
     d = datetime.now(tz=timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     reply = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
     self.assertEqual(ReplyCRUD.saveReply(reply, ReplyDataStrategy), {"result": "success", "value": 1})
     reply.replyId = 1
     self.assertEqual(ReplyCRUD.cancelReply(reply, ReplyDataStrategy), {"result": "success"})
     replyToTest = ReplyCRUD.getReplyByReplyId(1, ReplyDataStrategy)
     self.assertEqual(replyToTest.sentStatus, "cancelled")
示例#15
0
 def test_userCanBeEdited(self):
     mockUserDataStrategy = Mock()
     mockUserDataStrategyAttrs = {"saveUser.return_value": 1,
             "updateUser.return_value": True}
     mockUserDataStrategy.configure_mock(**mockUserDataStrategyAttrs)
     userToTest = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)), userId = 1)
     self.assertEqual(UserCRUD.updateUser(userToTest, mockUserDataStrategy), {"result": "success"})
     userToTest = User('test', '', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)), userId = 1)
     self.assertEqual(UserCRUD.updateUser(userToTest, mockUserDataStrategy), {"result": "error", "value": {"tokenError": "Token cannot be empty"}})
 def test_userCanBeRetrievedByUsername(self):
     userToSave = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)))
     UserCRUD.saveUser(userToSave, UserDataStrategy)
     userToTest = UserCRUD.getUserByUsername('test', UserDataStrategy)
     self.assertEqual(userToTest.username, 'test')
     self.assertEqual(userToTest.authToken, '123456-012e1')
     self.assertEqual(userToTest.secretToken, '123h4123asdhh123')
     self.assertEqual(userToTest.timeZone, timezone(timedelta(hours = 5, minutes = 30)))
     self.assertEqual(userToTest.userId, 1)
示例#17
0
def run_demo():
    """
    Acquire current time
    """
    now = datetime.now()
    print('Current time is :', now)
    
    #Create a datetime object
    dt = datetime(2016,3,3,23,33,40)
    print('datetime object :', dt)
    
    #Convert from datetime object to timestamp. Timestamp is global unique.
    ts = dt.timestamp()
    print('Timestamp of 2016-03-03-23:33:40 is: ', ts)
    
    #Convert from timestamp to datetime object
    dt_r = datetime.fromtimestamp(ts)
    print('Datetime convert from timestamp is: ', dt_r)
    
    #Adjust to UTC time
    dt_utc = datetime.utcfromtimestamp(ts)
    print('UTC time is: ', dt_utc)
    
    #Create datetime from string
    dt_s = datetime.strptime('2016-3-3 23:45:23', '%Y-%m-%d %H:%M:%S')
    print('Time convert from string is: ', dt_s)
    
    #Create string from datetime
    s_dt = now.strftime('%a, %b %d %H:%M')
    print('Time convert to string is: ', s_dt)
    
    #Time offset operation. Use current time as basis.
    t_p = now + timedelta(hours = 10)
    print('Time after 10 hours is: ',t_p)
    t_m = now - timedelta(days = 1)
    print('Time before a day is: ', t_m)
    t_d = now + timedelta(days = 2, hours = 5)
    print('Time after 2 days and 5 hours: ', t_d)
    
    #Convert local time to UTC time. 
    tz_utc_8 = timezone(timedelta(hours = 8))
    dt_8 = now.replace(tzinfo = tz_utc_8)
    print('UTC time: ', dt_8)
    
    """
    Timezone convertion. 
    Set one kind of time as basis, then use astimezone complete convertion.
    """
    utc_dt = datetime.utcnow().replace(tzinfo = timezone.utc)
    print('UTC timezone: ', utc_dt)
    bj_dt = utc_dt.astimezone(timezone(timedelta(hours = 8)))
    print('Beijing time: ', bj_dt)
    tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours = 9)))
    print('Tokyo time: ', tokyo_dt)
    tokyo_dt = bj_dt.astimezone(timezone(timedelta(hours = 9)))
    print('Tokyo time: ', tokyo_dt)
示例#18
0
 def test_messageIsBrokenDownCorrectlyBeforeSendingWhenContainingLinks(self, patchMethod, urlLengthPatch):
     user = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)))
     patchMethod.return_value = "example"
     urlLengthPatch.return_value = (23,23)
     mockUserDataStrategy = Mock()
     mockUserDataStrategyAttrs = {"getUserById.return_value": user }
     mockUserDataStrategy.configure_mock(**mockUserDataStrategyAttrs)
     d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToSend = Reply(1, "... Facebook biased - when did people give up on the process of getting informed? http://blog.theoldreader.com/post/144197778539/facebook-biased via @theoldreader", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
     self.assertEqual(MessageBreaker.breakMessage(replyToSend.message, replyToSend.tweetId, 1, mockUserDataStrategy), ["... Facebook biased - when did people give up on the process of getting informed? http://blog.theoldreader.com/post/144197778539/facebook-biased via @theoldreader"])
 def test_repliesCanBeRetrievedByUserId(self, scheduleReplyPatch):
     d = datetime.now(tz=timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     reply = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
     self.assertEqual(ReplyCRUD.saveReply(reply, ReplyDataStrategy), {"result": "success", "value": 1})
     self.assertEqual(ReplyCRUD.saveReply(reply, ReplyDataStrategy), {"result": "success", "value": 2})
     self.assertEqual(ReplyCRUD.saveReply(reply, ReplyDataStrategy), {"result": "success", "value": 3})
     reply.userId = 2
     self.assertEqual(ReplyCRUD.saveReply(reply, ReplyDataStrategy), {"result": "success", "value": 4})
     repliesToTest = ReplyCRUD.getRepliesByUserId(1, ReplyDataStrategy)
     self.assertEqual(len(repliesToTest), 3)
示例#20
0
 def test_repliesCanBeRetrievedByUserIdAndStatus(self):
     d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replies = [
             Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1),
             Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 2)
             ]
     mockReplyDataStrategy = Mock()
     mockReplyDataStrategyAttrs = {"getRepliesByUserIdAndStatus.return_value": replies}
     mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
     self.assertEqual(ReplyCRUD.getRepliesByUserIdAndStatus(1, "unsent", mockReplyDataStrategy), replies)
 def test_replyCanBeUpdated(self, removeReplyPatch, scheduleReplyPatch, updateReplyPatch):
     d = datetime.now(tz=timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToSave = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
     self.assertEqual(ReplyCRUD.saveReply(replyToSave, ReplyDataStrategy), {"result": "success", "value": 1})
     replyToUpdate = Reply(
         1, "@example an example message please", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId=1
     )
     self.assertEqual(ReplyCRUD.updateReply(replyToUpdate, ReplyDataStrategy), {"result": "success"})
     replyToTest = ReplyCRUD.getReplyByReplyId(1, ReplyDataStrategy)
     self.assertEqual(replyToTest.message, "@example an example message please")
    def setUp(self):
        userToTest = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)), userId = 1)
        self.mentionsToReturn = ['a'] * 10
        self.d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30)))
        self.repliesToReturn = [
                Reply(1, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =1),
                Reply(1, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =2),
                Reply(1, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =3), 
                Reply(2, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =4), 
                Reply(2, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =5), 
                Reply(1, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =6, sentStatus="sent"), 
                Reply(1, "@example an example message", self.d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId =7, sentStatus="cancelled"), 
                ]

        def returnReplies(userId, status=""):
            if status == "":
                return [reply for reply in self.repliesToReturn if reply.userId == userId]
            else:
                return [reply for reply in self.repliesToReturn if reply.userId == userId and reply.sentStatus == status]

        self.mockUserDataStrategy = Mock()
        self.mockUserDataStrategyAttrs = {"getUserById.return_value": userToTest 
}
        self.mockUserDataStrategy.configure_mock(**self.mockUserDataStrategyAttrs)
        
        self.mockReplyDataStrategy = Mock()
        self.mockReplyDataStrategyAttrs = {"saveReply.return_value": 1,
                "getRepliesByUserId.side_effect": returnReplies,
                "getReplyByReplyId.return_value": self.repliesToReturn[1],
                "getRepliesByUserIdAndStatus.side_effect": returnReplies,
                "cancelReply.return_value": True}
        self.mockReplyDataStrategy.configure_mock(**self.mockReplyDataStrategyAttrs)
        DataConfig.UserDataStrategy = self.mockUserDataStrategy
        DataConfig.ReplyDataStrategy = self.mockReplyDataStrategy
示例#23
0
 def get_timezone(self, ctx):
     """
         Returns a timezone object with the offset to use for the given context.
     :param ctx: commands.Context object
     :return: Timezone object for the context
     """
     if self.database.is_connected():
         if ctx.guild is not None:
             timezone = self.database.get_guild_options(ctx.guild.id).timezone
             return dt.timezone(dt.timedelta(hours=utils.tz_map[timezone.upper()]), timezone.upper())
     return dt.timezone(dt.timedelta(), "UTC")
示例#24
0
def start_and_end_of_lesson(class_number):
    if class_number == 1:
        return (datetime.time(9,30,0,0,datetime.timezone(datetime.timedelta(hours=3))), datetime.time(11,5,0,0,datetime.timezone(datetime.timedelta(hours=3))))
    elif class_number == 2:
        return (datetime.time(11,15,0,0,datetime.timezone(datetime.timedelta(hours=3))), datetime.time(12,50,0,0,datetime.timezone(datetime.timedelta(hours=3))))
    elif class_number == 3:
        return (datetime.time(13,50,0,0,datetime.timezone(datetime.timedelta(hours=3))), datetime.time(15,25,0,0,datetime.timezone(datetime.timedelta(hours=3))))
    elif class_number == 2:
        return (datetime.time(15,35,0,0,datetime.timezone(datetime.timedelta(hours=3))), datetime.time(17,10,0,0,datetime.timezone(datetime.timedelta(hours=3))))
    elif class_number == 2:
        return (datetime.time(17,20,0,0,datetime.timezone(datetime.timedelta(hours=3))), datetime.time(18,55,0,0,datetime.timezone(datetime.timedelta(hours=3))))
示例#25
0
def to_timestamp(dt_str, tz_str):
    d_time = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
    t_zone = re.match(r'^UTC(\+|-)([0][0-9]|[1][0-4]|[0-9]):00$', tz_str)
    print(d_time, t_zone.group(1))
    hour = int(t_zone.group(1)+t_zone.group(2))
    d_t = d_time.replace(tzinfo=timezone(timedelta(hours=hour)))  # 转化为带时区的时间
    print(d_time.timestamp())
    print(d_t, type(d_t))
    d_utc = d_t.astimezone(timezone(timedelta(hours=0)))
    print(d_utc)
    print(d_utc.timestamp())
 def test_replyCanBeRetrievedById(self, scheduleReplyPatch):
     d = datetime.now(tz=timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToSave = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
     self.assertEqual(ReplyCRUD.saveReply(replyToSave, ReplyDataStrategy), {"result": "success", "value": 1})
     replyToTest = ReplyCRUD.getReplyByReplyId(1, ReplyDataStrategy)
     self.assertEqual(replyToTest.userId, 1)
     self.assertEqual(replyToTest.message, "@example an example message")
     self.assertEqual(replyToTest.scheduledTime, d)
     self.assertEqual(replyToTest.timeZone, timezone(timedelta(hours=5, minutes=30)))
     self.assertEqual(replyToTest.tweetId, "134953292")
     self.assertEqual(replyToTest.replyId, 1)
示例#27
0
 def test_userIsUpdatedInsteadOfSavingIfUserExists(self):
     mockUserDataStrategy = Mock()
     userToTest = User('test', '123456-012e1', '123h4123asdhh123', timezone(timedelta(hours = 5, minutes = 30)), userId = 1)
     userToSave = User('test', '1231lkjasd-12a', 'p99087676dsaanbwU', timezone(timedelta(hours = 0, minutes = 0)))
     mockUserDataStrategyAttrs = {"getUserByUsername.return_value": userToTest,
             "updateUser.return_value": True
             }
     mockUserDataStrategy.configure_mock(**mockUserDataStrategyAttrs)
     self.assertEqual(UserCRUD.saveUser(userToSave, mockUserDataStrategy), {"result": "success", "value": 1, "updated": True})
     self.assertTrue(mockUserDataStrategy.updateUser.called)
     #self.assertEqual(userToSave.timeZone, userToTest.timeZone)
     mockUserDataStrategy.getUserByUsername.assert_called_once_with('test')
示例#28
0
def convertRowToUser(row):
    timeZoneInformation = [row['timeZoneDifferenceDays'], row['timeZoneDifferenceSeconds']]
    if timeZoneInformation[0] == -1:
        tz = timezone(timedelta(seconds=row['timeZoneDifferenceSeconds'] * -1))
    else:
        tz = timezone(timedelta(seconds=row['timeZoneDifferenceSeconds']))
    userToReturn = User(row['username'],
            row['authToken'],
            row['secretToken'],
            tz,
            userId = row['ROWID'])
    return userToReturn
示例#29
0
 def test_repliesCanBeCancelled(self, removeReplyPatch):
     d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
     replyToUpdate = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
     newVersionOfReply = deepcopy(replyToUpdate)
     mockReplyDataStrategy = Mock()
     mockReplyDataStrategyAttrs = {"getReplyByReplyId.return_value": newVersionOfReply,
             "cancelReply.return_value": True, 
             }
     mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
     self.assertEqual(ReplyCRUD.cancelReply(replyToUpdate, mockReplyDataStrategy), {"result": "success"})
     self.assertEqual(replyToUpdate.sentStatus, "cancelled")
     removeReplyPatch.assert_called_once_with(1)
示例#30
0
def to_timestamp(dt_str, tz_str):
    print('the time you enter is ', dt_str)
    dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
    print('the time zone you enter is', tz_str)
    tz = re.match(r'UTC(\+|\-)(\d+):(\d+)', tz_str)
    if tz:
        print('time zone', tz.groups())
    print('test', int(tz.group(2)))
    tz_utc = timezone(timedelta(hours=int(tz.group(2)))) 
    tz_dt = dt.replace(tzinfo=tz_utc)
    utc_dt = tz_dt.astimezone(timezone(timedelta(hours=0)))   
    return utc_dt.timestamp()
示例#31
0
            q, r = divmod(
                timezone._timedelta_to_microseconds(a),
                timezone._timedelta_to_microseconds(b),
            )
            return q, timedelta(0, 0, r)

        @staticmethod
        def _name_from_offset(delta):
            if not delta:
                return "UTC"
            if delta < timedelta(0):
                sign = "-"
                delta = -delta
            else:
                sign = "+"
            hours, rest = timezone._divmod_timedeltas(delta,
                                                      timedelta(hours=1))
            minutes, rest = timezone._divmod_timedeltas(
                rest, timedelta(minutes=1))
            result = "UTC%s%02d:%02d" % (sign, hours, minutes)
            if rest.seconds:
                result += ":%02d" % (rest.seconds, )
            if rest.microseconds:
                result += ".%06d" % (rest.microseconds, )
            return result

        _maxoffset = timedelta(hours=23, minutes=59)
        _minoffset = -_maxoffset

    timezone.utc = timezone(timedelta(0))
示例#32
0
from datetime import date, datetime, timedelta, timezone

__all__ = ["is_weekend", "last_friday", "china_now"]

WEEKENDS = frozenset({5, 6})


def is_weekend(_date: date = None) -> bool:
    _date = _date or datetime.now().date()
    return _date.weekday() in WEEKENDS


def last_friday(_date: date = None) -> date:
    _date = _date or datetime.now().date()
    delta = timedelta(days=-(_date.weekday() + 3) % 7)
    return _date + delta


CHINA_TIMEZONE = timezone(timedelta(hours=8), name="UTC+8")


def china_now() -> datetime:
    return datetime.now(CHINA_TIMEZONE)
示例#33
0
def transTime(ts):
    dt = parser.parse(ts)
    cn_dt = dt.astimezone(timezone(timedelta(hours=8)))
    new_ts = cn_dt.strftime("%Y-%m-%d %H:%M:%S")
    return new_ts
from boto3.session import Session

ins = json.loads(input())
session = boto3.Session(
    aws_access_key_id='AKIAIXCQGQVC434OJILA',
    aws_secret_access_key=ins.get('secret'),
    region_name='ap-northeast-1',
)
ec2 = session.resource('ec2', region_name='ap-northeast-1')

response = session.client('ec2').describe_instances()
logs = []
for reserv in response["Reservations"]:
    #pprint(reserv, indent=2)
    instances = reserv.get('Instances')
    for instance in instances:
        tags = instance.get('Tags')
        state = instance.get('State')
        types = instance.get('InstanceType')
        log = {'tags': tags, 'state': state, 'types': types}
        logs.append(log)
#print( json.dumps(logs,indent=2,ensure_ascii=False))

jst_zone = timezone(timedelta(hours=+9), 'JST')
now = datetime.now(jst_zone).strftime('%Y-%m-%d_%H:%M:%S')
keyname = 'aws-machines-stats/machine_stat_{now}.json'.format(now=now)
obj = session.resource('s3').Object('cloud-status-stats', keyname)
body = json.dumps(logs, indent=2, ensure_ascii=False)
obj.put(Body=bytes(body, 'utf8'))
print('ok')
示例#35
0
    def current_conditions_by_loc(self, lat=None, lon=None):
        """
        Will return current weather conditions
        
        Keyword Arguments:
            lat {float} -- Latitude (default: {None})
            lon {float} -- Longitude (default: {None})
        
        Raises:
            KeyError -- lat and lon should be specified
            Exception -- returns exception error if response is not returned with code 200/OK
        
        Returns:
            Pandas df -- Dataframe with current conditions for given lat and lon
        """

        if lat is None or lon is None:
            raise KeyError("Please specify Latitude and Longitude")

        # For api request
        request = self.api_host + f"/v2/weather/locations/{str(lat)},{str(lon)}/currentconditions"
        # Get response, validate with header
        response = requests.get(request, headers=self.api_header)
        if response.ok:
            # data structure
            data = {
                "date": "",
                "time": "",
                "lat": 0.0,
                "lon": 0.0,
                "conditions_code": "",
                "cloud_conditions": "",
                "wind_conditions": "",
                "rain_conditions": "",
                "conditions_text": "",
                "temp": 0,
                "precipitation": 0,
                "solar": 0,
                "relative_humidity": 0,
                "wind_amount": 0,
                "wind_bearind": 0,
                "wind_direction": ""
            }

            response_data = response.json()
            date_time = datetime.fromisoformat(
                response_data.get('dateTime')).replace(
                    tzinfo=timezone(timedelta(0)))
            data['date'] = date_time.date()
            data['time'] = date_time.time()
            data['lat'] = response_data.get("location").get("latitude")
            data['lon'] = response_data.get("location").get("longitude")
            data['conditions_code'] = response_data.get("conditionsCode")
            data['cloud_conditions'] = data['conditions_code'][0]
            data['rain_conditions'] = data['conditions_code'][1]
            data['wind_conditions'] = data['conditions_code'][2]
            data['conditions_text'] = response_data.get("conditionsText")
            data['temp'] = response_data.get("temperature", {}).get("amount")
            data['precipitation'] = response_data.get("precipitation",
                                                      {}).get("amount")
            data['solar'] = response_data.get("solar", {}).get("amount")
            data['wind_amount'] = response_data.get("wind", {}).get("amount")
            data['wind_bearing'] = response_data.get("wind", {}).get("bearing")
            data['wind_direction'] = response_data.get("wind",
                                                       {}).get("direction")

            return data
        else:
            raise Exception(
                "Api call returned error with {0} status code".format(
                    response.status_code))
示例#36
0
class Remind:
    DATABASE = 'reminder.db'
    FILE_PATH = join(dirname(__file__), 'files' + os.sep + DATABASE)
    STATUS_FINISHED = 'Finished'
    STATUS_CANCELED = 'Canceled'
    JST = timezone(timedelta(hours=+9), 'JST')
    REMIND_CONTROL_CHANNEL = 'remind_control_channel'

    def __init__(self, bot):
        self.bot = bot
        self.remind_date = None  # リマインドする日付
        self.remind_time = None  # リマインドする時刻
        self.remind_message = ''  # リマインドするメッセージ
        self.remind_mention = None  # リマインド時のメンション
        self.repeat = False  # 繰り返しするかどうか
        self.repeat_interval = None
        self.remind_rows = None  # リマインドの結果
        self.aes = Aes_angou(setting.DISCORD_TOKEN)

    async def prepare(self):
        '''
        sqlite3のdbを準備する
        '''
        # Herokuの時のみ、チャンネルからファイルを取得する
        await self.get_discord_attachment_file()

        if not os.path.exists(self.aes.ENC_FILE_PATH):
            conn = sqlite3.connect(self.FILE_PATH)
            with conn:
                cur = conn.cursor()

                create_table_sql = '''
                                    create table if not exists reminder_table (
                                        id integer primary key autoincrement,
                                        remind_datetime datetime,
                                        guild integer,
                                        member integer,
                                        channel integer,
                                        remind_message text,
                                        status text,
                                        repeat_count integer,
                                        repeat_max_count integer,
                                        repeat_flg text,
                                        repeat_interval text,
                                        created_at datetime,
                                        updated_at datetime
                                    )
                                    '''
                cur.execute(create_table_sql)
        else:
            self.decode()
        self.read()
        self.encode()
        LOG.info('準備完了')

    async def get_discord_attachment_file(self):
        # HerokuかRepl.itの時のみ実施
        if setting.IS_HEROKU or setting.IS_REPLIT:
            # 環境変数によって、添付ファイルのファイル名を変更する
            file_name = self.aes.ENC_FILE if setting.KEEP_DECRYPTED_FILE else self.DATABASE
            LOG.debug('Heroku mode.start get_discord_attachment_file.')
            # ファイルをチェックし、存在しなければ最初と見做す
            file_path_first_time = join(dirname(__file__), 'files' + os.sep + 'first_time')
            if (setting.IS_HEROKU and not os.path.exists(file_path_first_time)) or setting.IS_REPLIT:
                if setting.IS_HEROKU:
                    with open(file_path_first_time, 'w') as f:
                        now = datetime.datetime.now(self.JST)
                        f.write(now.strftime('%Y/%m/%d(%a) %H:%M:%S'))
                        LOG.debug(f'{file_path_first_time}が存在しないので、作成を試みます')
                attachment_file_date = None

                # BotがログインしているGuildごとに繰り返す
                for guild in self.bot.guilds:
                    # チャンネルのチェック
                    LOG.debug(f'{guild}: チャンネル読み込み')
                    get_control_channel = discord.utils.get(guild.text_channels, name=self.REMIND_CONTROL_CHANNEL)
                    if get_control_channel is not None:
                        messages = await get_control_channel.history(limit=20).flatten()

                        for message in messages:
                            LOG.debug(f'con: {message.content}, attchSize:{len(message.attachments)}')
                            # message_created_at_jst = datetime.datetime(message.created_at, tzinfo=self.JST)
                            message_created_at = message.created_at.replace(tzinfo=timezone.utc)
                            message_created_at_jst = message_created_at.astimezone(self.JST)

                            if attachment_file_date is not None:
                                LOG.debug(f'date: {attachment_file_date} <<<<<<< {message_created_at_jst}, {attachment_file_date < message_created_at_jst}')
                            # file_nameが本文である場合、ファイルを取得する
                            if message.content == file_name:
                                if len(message.attachments) > 0:
                                    # 日付が新しい場合、ファイルを取得
                                    if attachment_file_date is None or attachment_file_date < message_created_at_jst:
                                        attachment_file_date = message_created_at_jst
                                        file_path = join(dirname(__file__), 'files' + os.sep + file_name)
                                        await message.attachments[0].save(file_path)
                                        LOG.info(f'channel_file_save:{guild.name} / datetime:{attachment_file_date.strftime("%Y/%m/%d(%a) %H:%M:%S")}')
                                        break
                    else:
                        LOG.warning(f'{guild}: に所定のチャンネルがありません')
            else:
                LOG.debug(f'{file_path_first_time}が存在します')

            LOG.debug('get_discord_attachment_file is over!')

    async def set_discord_attachment_file(self, guild):
        # HerokuかRepl.itの時のみ実施
        if setting.IS_HEROKU or setting.IS_REPLIT:
            # 環境変数によって、添付ファイルのファイル名を変更する
            file_name = self.aes.ENC_FILE if setting.KEEP_DECRYPTED_FILE else self.DATABASE
            LOG.debug('Heroku mode.start set_discord_attachment_file.')

            # チャンネルをチェック(チャンネルが存在しない場合は勝手に作成する)
            get_control_channel = discord.utils.get(guild.text_channels, name=self.REMIND_CONTROL_CHANNEL)
            if get_control_channel is None:
                permissions = []
                target = []
                permissions.append(discord.PermissionOverwrite(read_messages=False,read_message_history=False))
                target.append(guild.default_role)
                permissions.append(discord.PermissionOverwrite(read_messages=True,read_message_history=True))
                target.append(self.bot.user)
                overwrites = dict(zip(target, permissions))

                try:
                    get_control_channel = await guild.create_text_channel(name=self.REMIND_CONTROL_CHANNEL, overwrites=overwrites)
                    LOG.info(f'***{self.REMIND_CONTROL_CHANNEL}を作成しました!***')
                except discord.errors.Forbidden:
                    msg = f'***{self.REMIND_CONTROL_CHANNEL}の作成に失敗しました!***'
                    LOG.error(msg)
                    raise

                if get_control_channel is None:
                    LOG.error(f'なんらかのエラーが発生しました')
                    return

            # チャンネルの最後のメッセージを確認し、所定のメッセージなら削除する
            last_message = await get_control_channel.history(limit=1).flatten()
            if len(last_message) != 0:
                if last_message[0].content == file_name:
                    await get_control_channel.purge(limit=1)

            # チャンネルにファイルを添付する
            file_path = join(dirname(__file__), 'files' + os.sep + file_name)
            await get_control_channel.send(file_name, file=discord.File(file_path))
            LOG.info(f'***{get_control_channel.name}へファイルを添付しました!***')

            LOG.debug('set_discord_attachment_file is over!')

    def decode(self):
        if os.path.exists(self.aes.ENC_FILE_PATH):
            self.aes.decode()
            os.remove(self.aes.ENC_FILE_PATH)

    def encode(self):
        if os.path.exists(self.aes.DEC_FILE_PATH):
            self.aes.encode()
            if setting.KEEP_DECRYPTED_FILE:
                os.remove(self.aes.DEC_FILE_PATH)

    def read(self):
        # readはdecodeしない
        conn = sqlite3.connect(self.FILE_PATH)
        with conn:
            cur = conn.cursor()
            select_sql = '''select * from reminder_table where status = 'Progress' order by remind_datetime'''
            LOG.debug(select_sql)
            cur.execute(select_sql)
            self.remind_rows = cur.fetchmany(100)
            LOG.info('******読み込みが完了しました******')
            LOG.debug(self.remind_rows)

    async def make(self, guild_id, author_id, remind_datetime: datetime,
            remind_message: str, channel: int, status: str, repeat_flg: str,
            repeat_interval: str, repeat_count: int=1, repeat_max_count:int=None):
        '''remindを作成'''
        self.decode()
        conn = sqlite3.connect(self.FILE_PATH)
        id = None
        with conn:
            cur = conn.cursor()

            now = datetime.datetime.now(self.JST)

            insert_sql = 'INSERT INTO reminder_table (remind_datetime,guild,member,channel,remind_message,status,repeat_count,repeat_max_count,repeat_flg,repeat_interval,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)'
            remind_param = (remind_datetime, guild_id, author_id,
                            channel, remind_message, status, repeat_count, repeat_max_count,
                            repeat_flg, repeat_interval, now, now)

            # Insert a row of data
            cur.execute(insert_sql, remind_param)
            LOG.debug(insert_sql)

            # get id
            get_id_sql = 'select id from reminder_table where rowid = last_insert_rowid()'
            cur.execute(get_id_sql)
            id = cur.fetchone()[0]
            LOG.debug(f'id:{id}を追加しました')
            conn.commit()
            self.read()
        self.encode()
        # Herokuの時のみ、チャンネルにファイルを添付する
        guild = discord.utils.get(self.bot.guilds, id=guild_id)
        await self.set_discord_attachment_file(guild)
        return id

    async def update_status(self, remind_id: int, guild_id: int, status: str=STATUS_FINISHED):
        '''remindのステータスを変更'''
        self.decode()

        conn = sqlite3.connect(self.FILE_PATH)
        with conn:
            now = datetime.datetime.now(self.JST)

            remind_param = (status, now, remind_id)
            update_sql = 'update reminder_table set status=?, updated_at = ? where id = ?'
            LOG.debug(update_sql)
            conn.execute(update_sql, remind_param)
            LOG.info(f'id:{remind_id}を{status}にしました')
        self.read()
        self.encode()
        guild = discord.utils.get(self.bot.guilds, id=guild_id)
        await self.set_discord_attachment_file(guild)

    def list(self, ctx: commands.Context):
        self.decode()
        conn = sqlite3.connect(self.FILE_PATH)
        with conn:
            cur = conn.cursor()
            if ctx.guild is None:
                select_sql = f'''select * from reminder_table where status = 'Progress' and member = '{ctx.author.id}' order by remind_datetime'''
            else:
                select_sql = f'''select * from reminder_table where status = 'Progress' and guild = '{ctx.guild.id}' and member = '{ctx.author.id}' order by remind_datetime'''
            
            LOG.debug(select_sql)
            cur.execute(select_sql)
            rows = cur.fetchmany(100)
            message = ''
            for row in rows:
                repeat_message = '繰り返す' if row[9] == '1' else '繰り返さない'
                repeat_interval_message = f'({row[10]})' if row[10] is not None else ''
                message += f'No: {row[0]} Remind_datetime: {row[1]}\n'
                message += f'Message: {row[5]}\n'
                message += f'Status: {row[6]} {repeat_message}{repeat_interval_message}\n--\n'

            escaped_mention_text = '(データがありません)' if len(message) == 0 else discord.utils.escape_mentions(message)
            LOG.debug(escaped_mention_text)
        self.encode()
        return escaped_mention_text

    def list_all_guild(self, ctx: commands.Context):
        return self._list_all_func(ctx, True)

    def list_all(self, ctx: commands.Context):
        return self._list_all_func(ctx, False)

    def _list_all_func(self, ctx: commands.Context, is_guild: bool):
        self.decode()
        conn = sqlite3.connect(self.FILE_PATH)
        with conn:
            cur = conn.cursor()

            select_sql = 'select * from reminder_table '
            if is_guild:
                select_sql += f'''where guild = '{ctx.guild.id}' '''
            select_sql += 'order by updated_at desc'
            LOG.debug(select_sql)

            cur.execute(select_sql)
            rows = cur.fetchmany(100)
            message = ''
            for row in rows:
                repeat_message = '繰り返す' if row[9] == '1' else '繰り返さない'
                repeat_interval_message = f'({row[10]})' if row[10] is not None else ''
                message += f'No: {row[0]} Remind_datetime: {row[1]}\n'
                message += f'Message: {row[5]}\n'
                message += f'Status: {row[6]} {repeat_message}{repeat_interval_message}\n--\n'
            escaped_mention_text = '(データがありません)' if len(message) == 0 else discord.utils.escape_mentions(message)
            LOG.debug(escaped_mention_text)
        self.encode()
        chopped_escaped_mention_text = escaped_mention_text[:1900] + ('...(省略)...' if escaped_mention_text[1900:] else '')
        return chopped_escaped_mention_text

    def get(self, ctx: commands.Context, id: int):
        self.decode()
        conn = sqlite3.connect(self.FILE_PATH)
        with conn:
            cur = conn.cursor()
            select_sql = f'''select * from reminder_table where status = 'Progress' and member = '{ctx.author.id}' and id = '{id}' '''
            LOG.debug(select_sql)
            cur.execute(select_sql)
            row = cur.fetchone()
            escaped_mention_text = '(データがありません)' if row is None else discord.utils.escape_mentions(str(row))
            LOG.debug(escaped_mention_text)
        self.encode()
        return row
示例#37
0
from datetime import date, datetime, timedelta, timezone

import pytest

from fhirdatetime import FhirDateTime


def idfn(val):
    """Create a string ID for the test values."""
    return f" {val} "


# Handy timezones
utc = timezone.utc
ten_behind = timezone(timedelta(hours=-10))

eq = [
    (
        FhirDateTime(year=2020),
        FhirDateTime(year=2020),
    ),
    (
        FhirDateTime(year=2020, month=1),
        FhirDateTime(year=2020, month=1),
    ),
    (
        FhirDateTime(year=2020, month=1, day=6),
        FhirDateTime(year=2020, month=1, day=6),
    ),
    (
示例#38
0
    m = re.match("(帰国者・接触者相談センター相談件数|陽性患者属性|検査件数)", s)

    if m:

        xlsx_urls[m.group(0)] = urljoin(url, tds[2].find("a").get("href"))

# ファイルダウンロード

soudan_path = get_file(xlsx_urls["帰国者・接触者相談センター相談件数"], "soudan.xlsx", DOWNLOAD_DIR)
kensa_path = get_file(xlsx_urls["検査件数"], "kensa.xlsx", DOWNLOAD_DIR)
kanja_path = get_file(xlsx_urls["陽性患者属性"], "kanja.xlsx", DOWNLOAD_DIR)

# データラングリング

JST = datetime.timezone(datetime.timedelta(hours=+9), "JST")

dt_now = datetime.datetime.now(JST)
dt_update = dt_now.strftime("%Y/%m/%d %H:%M")

data = {"lastUpdate": dt_update}

# contacts
df_soudan = pd.read_excel(soudan_path, engine="openpyxl", parse_dates=["受付_年月日"])

df_soudan.set_index("受付_年月日", inplace=True)

ser_contacts = pd.to_numeric(df_soudan["相談件数"], errors="coerce").dropna().astype(int)

df_contacts = pd.DataFrame({"小計": ser_contacts})
df_contacts["日付"] = df_contacts.index.strftime("%Y-%m-%d")
示例#39
0
def filter_dt(dt, offset, format_string):
	return datetime.fromtimestamp(dt, tz=timezone(timedelta(seconds=offset))).strftime(format_string)
示例#40
0
def upsert(request):
    """ポイントデータの新規作成"""
    # 返り値
    ok_result = {"statusCode": "200"}
    error_result = {"statusCode": "400"}
    # POSTのみ実行
    if request.method != "POST":
        error_result["message"] = "NOT POST"
        return JsonResponse(error_result)
    else:
        # BodyのJsonをロード
        body_json = (request.body).decode('utf-8')
        body = json.loads(body_json)
        # Key項目の存在確認
        if body.get("to_username") is None \
            or body.get("from_username") is None \
            or body.get("point") is None \
            or body.get("type") is None:
            error_result["message"] = "NO DATA"
            return JsonResponse(error_result)
        else:
            to_username = body.get("to_username")
            from_username = body.get("from_username")
            point = body.get("point")
            ptype = body.get("type")
            JST = timezone(timedelta(hours=+9), 'JST')
            now = datetime.now(JST)
            time_stamp = int(now.strftime('%s'))
            today = datetime(now.year, now.month, now.day, 0, 0, 0, 0)
            today_s = int(today.strftime('%s'))
            today_yymmdd = today.strftime('%Y-%m-%d')
            try:
                # DynamoDBにインサート
                insert(to_username, from_username, point, ptype, time_stamp)

                # 本日のもらったポイントについての集計
                today_data = today_to_query(to_username, today_s)
                #ok_result["data"] = today_data
                to_point_sum = 0
                for record in today_data["Items"]:
                    to_point_sum += record["point"]
                data = {
                    "username": HrUser(username=to_username),
                    "date": today_yymmdd,
                    "point": to_point_sum,
                    "delete_flg": "0"
                }
                ToPointDay.objects.update_or_create(
                    username=HrUser(username=to_username),
                    date=today_yymmdd,
                    defaults=data)

                # 本日の送ったポイントについての集計
                today_data = today_from_query(from_username, today_s)
                from_point_sum = 0
                for record in today_data["Items"]:
                    from_point_sum += record["point"]
                data = {
                    "username": HrUser(username=from_username),
                    "date": today_yymmdd,
                    "point": from_point_sum,
                    "delete_flg": "0"
                }
                FromPointDay.objects.update_or_create(
                    username=HrUser(username=from_username),
                    date=today_yymmdd,
                    defaults=data)

                return JsonResponse(ok_result)
            except:
                ex, ms, tb = sys.exc_info()
                error_result["message"] = format(ms)
                return JsonResponse(error_result)
示例#41
0
 def test_date_no_command(self, mocker) -> None:
     mock = mocker.patch("subprocess.check_call")
     dt = datetime.fromtimestamp(1525270801, timezone(timedelta(hours=4)))
     autosuspend.notify_suspend(None, "not this", dt)
     mock.assert_not_called()
示例#42
0
 def test_smoke(self, mocker) -> None:
     mock = mocker.patch("subprocess.check_call")
     dt = datetime.fromtimestamp(1525270801, timezone(timedelta(hours=4)))
     autosuspend.schedule_wakeup("echo {timestamp:.0f} {iso}", dt)
     mock.assert_called_once_with(
         "echo 1525270801 2018-05-02T18:20:01+04:00", shell=True)
示例#43
0
文件: utils.py 项目: varikmp/cpython
def parsedate_to_datetime(data):
    *dtuple, tz = _parsedate_tz(data)
    if tz is None:
        return datetime.datetime(*dtuple[:6])
    return datetime.datetime(*dtuple[:6],
            tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
示例#44
0
cStr = datetime.datetime.strftime(datetime.datetime.now(),'%a %b %d %H:%M')
print('\n转换为str=',cStr)


# datetime加减  一个timedalta对象代表了一个时间差
now = datetime.datetime.now()
print('datetime加',now + datetime.timedelta(hours =10))
print('datetime减',now - datetime.timedelta(hours =10))

print('datetime日期加',now + datetime.timedelta(hours =10,days=1))



# 本地时间转换UTC时间
tz_utc_8 = datetime.timezone(datetime.timedelta(hours=-7))
print('\nUTC+7 =',now)
print('\nUTC+7 =',now.replace(tzinfo=tz_utc_8))   # replace 只是更换时区,时分秒不会发生变化
print('\nUTC+7 =',now.astimezone(tz_utc_8))       # 时区间进行切换,发生变化

# 时区转换utcnow()
tz_utc = datetime.timezone.utc
utc_dt = datetime.datetime.utcnow()   # 获取UTC时间
print('\nutc时区=',tz_utc)
print('utc时间',utc_dt,'强制添加时区为UTC',datetime.datetime.utcnow().replace(tzinfo=tz_utc))

bj_dt = utc_dt.astimezone(datetime.timezone(datetime.timedelta(hours=8)))
print('北京时间',bj_dt)
tokyo_dt = utc_dt.astimezone(datetime.timezone(datetime.timedelta(hours=9)))
print('东京时间',tokyo_dt)
示例#45
0
print(timestamp)  # 输出:1465164360.0 小数点后为毫秒

t_timestamp = 1465164360.0
t_datetime = datetime.fromtimestamp(t_timestamp)  # timestamp 转换为datetime 本地时间
print(t_datetime)  # 输出:2016-06-06 06:06:00
t_utc_datetime = datetime.utcfromtimestamp(
    t_timestamp)  # timestamp 转换为utc datetime utc时间
print(t_utc_datetime)  # 输出:2016-06-05 22:06:00 可以用于时区转换

# 时区转换相关
# 拿到UTC时间,并强制设置时区为UTC+0:00:
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print('utc_dt is {}'.format(utc_dt))

# astimezone()将转换时区为北京时间:
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print('bj_dt is {}'.format(bj_dt))

# astimezone()将转换时区为东京时间:
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
print('tokyo_dt is {}'.format(tokyo_dt))

# astimezone()将bj_dt转换时区为东京时间:
tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))
print('tokyo_dt2 is {}'.format(tokyo_dt2))
# 上述输出:
# utc_dt is 2017-06-09 09:09:19.497633+00:00
# bj_dt is 2017-06-09 17:09:19.497633+08:00
# tokyo_dt is 2017-06-09 18:09:19.497633+09:00
# tokyo_dt2 is 2017-06-09 18:09:19.497633+09:00
示例#46
0
文件: start.py 项目: SR074/iperf3
    'host': config_ini['mysql']['Host'],
    'port': config_ini['mysql']['Port'],
    'database': config_ini['mysql']['Database'],
}

print('connect mysql')
cnx = mysql.connector.connect(**config)
cnx.ping(reconnect=True)
cursor = cnx.cursor()

host_id = config_ini['dbData']['HostId']
remote_id = config_ini['dbData']['RemoteId']

send_bytes = res_json['end']['sum_sent']['bytes']
send_bps = res_json['end']['sum_sent']['bits_per_second']
receive_bytes = res_json['end']['sum_received']['bytes']
receive_bps = res_json['end']['sum_received']['bits_per_second']
cpu_util_host = res_json['end']['cpu_utilization_percent']['host_total']
cpu_util_remote = res_json['end']['cpu_utilization_percent']['remote_total']
timestamp = res_json['start']['timestamp']['time']
created = datetime.now(timezone(timedelta(hours=+9), 'JST'))

sql = 'insert into results (host_id, remote_id, send_bytes, send_bps, receive_bytes, receive_bps, cpu_util_host, cpu_util_remote, timestamp, created) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
cursor.execute(
    sql, (host_id, remote_id, send_bytes, send_bps, receive_bytes, receive_bps,
          cpu_util_host, cpu_util_remote, timestamp, created))

cursor.close()
cnx.close()
print('end')
# importing packages
import pandas as pd
from datetime import timedelta, datetime, timezone, date
from dateutil import tz

# printing year from date objct
list1 = [date(2016, 10, 25), date(2000, 7, 21)]
print("year is", list1[1].year)

# counting no. of days upto 200 days from 21-07-2020
d1 = date(2020, 7, 21)
td = timedelta(days=200)
print("Date after 200 days from 21st July 2020 is:", d1 + td)

# timezones
EDT = timezone(timedelta(hours=-7))
dt = datetime(2020, 6, 19, 2, 38, 10, tzinfo=EDT)
IST = timezone(timedelta(hours=5, minutes=30))
print("The time in India is", dt.astimezone(IST),
      "when time in California was ", dt.astimezone(EDT))

# code to find timezone
IST1 = tz.gettz('Asia/Kolkata')
date = datetime(2020, 6, 19, 15, 49, 10, tzinfo=IST1)
print(date)

# reading dates from csv files
df = pd.read_csv('AirQuality.csv', parse_dates=['lastupdate'])
print(df['lastupdate'].head(5))
示例#48
0
 def test_fulltypename(self):
     v = DlTimestamp(
         datetime.datetime(
             2020, 9, 17, 14, 3, 12, 456789,
             datetime.timezone(datetime.timedelta(seconds=3600))))
     self.assertEqual(v.fulltypename, "TIMESTAMP")
示例#49
0
# cursor
# def onmousemove(event):
#   ax.lines = [ax.lines[0]]
#   ax.axvline(x=event.xdata, color="k")
# fig.canvas.mpl_connect('motion_notify_event', onmousemove)


# format the ticks
years = dates.YearLocator()   # every year
months = dates.MonthLocator()  # every month
years_fmt = dates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)
ax.format_xdata = dates.DateFormatter('%Y-%m-%d %H:%M', tz=datetime.timezone(datetime.timedelta(hours=-3)))
ax.format_ydata = lambda x: '%f' % x  # format the price.
ax.grid(True)

# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()

for participanttitle in first10participantitles:
    print(participanttitle)
    print('Votos: ', titletovotecount[participanttitle])
    print('Diferenca maxima: ', titletovotemaxdiff[participanttitle])
    print('Diferenca minima: ', titletovotemindiff[participanttitle])
    print('')
    plt.plot('x', participanttitle, data=chartdf, label=participanttitle)
示例#50
0
def time_string():
    time = datetime.datetime.now(tz=datetime.timezone(
        datetime.timedelta(-1, 72000))).strftime("%b-%d-%I:%M%p")
    return f'NewYork {time}'
示例#51
0
 def test_jsonvalue(self):
     v = DlTimestamp(
         datetime.datetime(
             2020, 9, 17, 14, 3, 12, 456789,
             datetime.timezone(datetime.timedelta(seconds=3600))))
     self.assertEqual(v.jsonvalue, "2020-09-17 14:03:12.456789+0100")
示例#52
0
import re

from colorama import Fore, Style

WELCOME = ["********************************\r\n",
           "** Welcome to the BBS server. **\r\n",
           "********************************\r\n"]
ONLINE = "Client {}{{}}:{{}}{} starts the connection.".format(
    Fore.MAGENTA, Style.RESET_ALL)
OFFLINE = "Client {}{{}}:{{}}{} closes the connection.".format(
    Fore.MAGENTA, Style.RESET_ALL)
WAITING = Fore.YELLOW + "[ ... ]" + Style.RESET_ALL
COMPLETE = Fore.GREEN + "[ OK ]" + Style.RESET_ALL
ERROR = Fore.RED + "[ FAIL ]" + Style.RESET_ALL

TIMEZONE = datetime.timezone(datetime.timedelta(hours=8))

EXTRACT_NEW_POST_FORMAT = re.compile(r'.*--title (.*) --content (.*)')
EXTRACT_KEYWORD = re.compile(r'.*##(.*)')
EXTRACT_TITLE = re.compile(r'.*--title (.*)')

EXTRACT_MAIL = re.compile(r'.*--subject (.*) --content (.*)')
EXTRACT_CONTENT = re.compile(r'.*--content (.*)')
EXTRACT_COMMENT = re.compile(r'comment \d+ (.*)')


def error(*args):
    print(ERROR, *args)


def waiting(*args):
示例#53
0
 def test_typecode(self):
     v = DlTimestamp(
         datetime.datetime(
             2020, 9, 17, 14, 3, 12, 456789,
             datetime.timezone(datetime.timedelta(seconds=3600))))
     self.assertEqual(v.typecode, "z")
示例#54
0
    TIME_FORMAT = s0_key.attrib["TIME_FORMAT"].value_for
    assert len(TIME_FORMAT.related_to.dimensions) == 5


# Each entry is a tuple with 2 elements:
# 1. an instance of lxml.etree.Element to be parsed.
# 2. Either:
#   - A sdmx.model object, in which case the parsed element must match the
#     object.
#   - A string, in which case parsing the element is expected to fail, raising
#     an exception matching the string.
ELEMENTS = [
    # sdmxml._datetime()
    (  # with 5 decimal places
        E(qname("mes:Extracted"), "2020-08-18T00:14:31.59849+05:00"),
        datetime(2020, 8, 18, 0, 14, 31, 598490, tzinfo=timezone(timedelta(hours=5))),
    ),
    (  # with 7 decimal places
        E(qname("mes:Extracted"), "2020-08-18T01:02:03.4567891+00:00"),
        datetime(2020, 8, 18, 1, 2, 3, 456789, tzinfo=timezone.utc),
    ),
    (  # with "Z"
        E(qname("mes:Extracted"), "2020-08-18T00:14:31.59849Z"),
        datetime(2020, 8, 18, 0, 14, 31, 598490, tzinfo=timezone.utc),
    ),
    pytest.param(  # with 7 decimal places AND "Z"
        E(qname("mes:Extracted"), "2020-08-18T01:02:03.4567891Z"),
        datetime(2020, 8, 18, 1, 2, 3, 456789, tzinfo=timezone.utc),
        marks=pytest.mark.xfail(raises=XMLParseError),
    ),
    # sdmxml._facet()
示例#55
0
def parse_info(data, name):
    """ Parse event data into dictionary """

    cal = Calendar.from_ical(data)

    for ev in cal.subcomponents:
        estart = ev.decoded('DTSTART')
        eend = ev.decoded('DTEND')
        esummary = ev.decoded('SUMMARY').decode('UTF-8')
        if estart.__class__ != datetime:
            continue
        yield Event(calendar=name, start=estart, end=eend, summary=esummary)


if __name__ == '__main__':
    LOCAL_TIMEZONE = datetime.now(timezone(timedelta(0))).astimezone().tzinfo
    config = configparser.ConfigParser()
    config.read(os.path.expanduser('~/') + '.config/nextcloud_cal.ini')

    if len(sys.argv) > 1:
        today = isoparse(sys.argv[1])
        tdelta = timedelta(days=1)
    else:
        today = date.today()
        tdelta = timedelta(days=int(config['DEFAULT']['time_delta']))

    cal_filter = '|'.join(config['DEFAULT']['cals'].split(','))
    # create client
    client = caldav.DAVClient(
        config['DEFAULT']['url'],
        proxy=None,
示例#56
0
文件: serv1.py 项目: chjfth/trivials
import time
from datetime import datetime, tzinfo, timedelta, timezone
from flask import Flask, abort
from flask import request, make_response
from flask import send_file

app = Flask(__name__)

tzchina = timezone(timedelta(hours=8))
dt_expire = datetime(2020, 12, 30, 9, 2, 3, 0, tzchina)


@app.route('/')
def index():
    return '<h1>Demo server for [FLPY] CH 17!</h1>'


@app.route('/data/flags/<cc1>/<filename>')
def serv_flag(cc1, filename):
    time.sleep(1.0)  # 1 second sleep to simulate network delay

    if filename.endswith('.gif'):

        if cc1.upper() == 'US':  # simulate error
            abort(404)

        return "This is {}.gif".format(cc1)

    elif filename.endswith('.json'):

        body = """"tld_cc": ".{cc1}", 
示例#57
0
def date_now_bangkok():
    return str(datetime.now(timezone(timedelta(seconds=7 * 3600))))[0:10]
示例#58
0
 def test_as_tzinfo(self):
     time_zone = mommy.make(models.TimeZone, code="EET", utc_offset=120)
     self.assertEqual(time_zone.as_tzinfo, dt.timezone(dt.timedelta(hours=2), "EET"))
示例#59
0
 def __init__(self, name):
     JST = timezone(timedelta(hours=+9), 'JST')
     self.name = name + '_' + datetime.now(JST).strftime('%Y%m%d%H%M%S')
b = datetime.datetime(year=2010, month=2, day=6, hour=10, minute=20)
d = a - b # outputs datetime.timedelta 
d.total_seconds() # output number of seconds
datetime.date.today() + datetime.timedelta(weeks=3) # in three weeks time
datetime.timedelta(seconds=1)
datetime.timedelta(days=1)

# timedelta constructor
# instances store only days, seconds, microseconds
# while constructor accepsts almost everything from microseconds to weeks 


# timezone (optional)
# tzinfo object
datetime.timezone 
cet = datetime.timezone(datetime.timedelta(hours=1), "CET") # define a timezone
departure = datetime.datetime(year=2014, month=1, day=7, hour=11, minute=30, tzinfo=cet)
arrival = datetie.datetime(year=2014, month=1, day=8, hour=10, minute=30, tzinfo=datetime.timezone.utc)
str(arrival - departure) 


from datetime import datetime, timezone
now = datetime(2014, 8, 10, 18, 18, 30)

# convert utc to local time 
now_utc = now.replace(tzinfo=timezone.utc) # utc time 
now_local = now_utc.astimezone() # local time
print(now_local)

# convert local time to utc 
time_format = '%Y-%m-%d %H:%M:%S'