当前位置: 首页>>代码示例>>Python>>正文


Python date.strftime方法代码示例

本文整理汇总了Python中datetime.date.strftime方法的典型用法代码示例。如果您正苦于以下问题:Python date.strftime方法的具体用法?Python date.strftime怎么用?Python date.strftime使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime.date的用法示例。


在下文中一共展示了date.strftime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: log

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def log(self, action="", data=""):
        date = datetime.now()
        if action == "Error":
            msg = ('[Error] ') + date.strftime("%c") + ' - ' + str(data)
        elif action == "newline":
            msg = "\n"
        else:
            msg = ('[ Log ] ') + date.strftime("%c") + ' - ' + str(action) + str(data)
        filelogname = date.strftime("%m-%Y")
        for logpath in paths:
            self.logpath = paths['logpath']
        filelogpath = str(self.logpath) + filelogname + ".txt"
        if os.path.isfile(filelogpath):
            file = open(filelogpath, "a")
            file.write(msg + '\n')
            file.close()
        else:
            file = open(filelogpath, "w")
            file.write(msg + '\n')
            file.close()
        if action != "newline":
            print msg  # Console output 
开发者ID:laincode,项目名称:shodan-seeker,代码行数:24,代码来源:shodanseeker.py

示例2: save_means

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def save_means(means, date):
    """Save means atomically. Protocol 4
    """
    tstamp = date.strftime(".%Y-%m-%d") if date else ""
    pf = conf.pickledir / f"means{tstamp}.pkl"
    pft = pf.with_suffix(".tmp")
    if not means:
        log.error("No means to save")
        return
    log.info("Saving %d means to %s", len(means), pf)
    latest = max(m[0] for m in means.values())
    log.info("Latest mean: %s", latest)
    with pft.open("wb") as f:
        pickle.dump(means, f, protocol=4)
    pft.rename(pf)
    log.info("Saving completed")


# FIXME: for performance reasons we want to minimize heavy DB queries.
# Means are cached in a pickle file to allow restarts and we pick up where
# we stopped based on measurement_start_time. Yet the timestamp are untrusted
# as they are generated by the probes. 
开发者ID:ooni,项目名称:pipeline,代码行数:24,代码来源:detector.py

示例3: format_date

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def format_date(self, date):
        if self._date_format == "None":
            return date
        return date.strftime(self._date_format) 
开发者ID:eyesoft,项目名称:home-assistant-custom-components,代码行数:6,代码来源:__init__.py

示例4: serialize_date

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def serialize_date(date):
    return date.strftime("%Y-%m-%d") 
开发者ID:mirumee,项目名称:ariadne,代码行数:4,代码来源:test_custom_scalars.py

示例5: cleanup_bag

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def cleanup_bag(bag_path, save=False):
    logger.info("Cleaning up bag dir: %s" % bag_path)
    if save:
        saved_bag_path = ''.join([bag_path, '_', datetime.strftime(datetime.now(), "%Y-%m-%d_%H.%M.%S")])
        logger.info("Moving bag %s to %s" % (bag_path, saved_bag_path))
        shutil.move(bag_path, saved_bag_path)
        return saved_bag_path
    else:
        shutil.rmtree(bag_path)
        return None 
开发者ID:fair-research,项目名称:bdbag,代码行数:12,代码来源:bdbag_api.py

示例6: extract_bag

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def extract_bag(bag_path, output_path=None, temp=False):
    if not os.path.exists(bag_path):
        raise RuntimeError("Specified bag path not found: %s" % bag_path)

    bag_dir = os.path.splitext(os.path.basename(bag_path))[0]
    if os.path.isfile(bag_path):
        if temp:
            output_path = tempfile.mkdtemp(prefix='bag_')
        elif not output_path:
            output_path = os.path.splitext(bag_path)[0]
            if os.path.exists(output_path):
                newpath = ''.join([output_path, '-', datetime.strftime(datetime.now(), "%Y-%m-%d_%H.%M.%S")])
                logger.info("Specified output path %s already exists, moving existing directory to %s" %
                            (output_path, newpath))
                shutil.move(output_path, newpath)
            output_path = os.path.dirname(bag_path)
        if zipfile.is_zipfile(bag_path):
            logger.info("Extracting ZIP archived file: %s" % bag_path)
            with open(bag_path, 'rb') as bag_file:
                zipped = zipfile.ZipFile(bag_file)
                zipped.extractall(output_path)
                zipped.close()
        elif tarfile.is_tarfile(bag_path):
            logger.info("Extracting TAR/GZ/BZ2 archived file: %s" % bag_path)
            tarred = tarfile.open(bag_path)
            tarred.extractall(output_path)
            tarred.close()
        else:
            raise RuntimeError("Archive format not supported for file: %s"
                               "\nSupported archive formats are ZIP or TAR/GZ/BZ2" % bag_path)

    extracted_path = os.path.join(output_path, bag_dir)
    logger.info("File %s was successfully extracted to directory %s" % (bag_path, extracted_path))

    return extracted_path 
开发者ID:fair-research,项目名称:bdbag,代码行数:37,代码来源:bdbag_api.py

示例7: getBatchName

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def getBatchName(y):
        now = datetime.now()
        year = int(now.strftime("%Y"))
        if y + 1 == year:
            return 'First Year Batch'
        elif y + 2 == year:
            return 'Second Year Batch'
        elif y + 3 == year:
            return 'Third Year Batch'
        elif y + 4 == year:
            return 'Fourth Year Batch' 
开发者ID:amfoss,项目名称:cms,代码行数:13,代码来源:StatusUpdateReporter.py

示例8: generateDidNotSendReport

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def generateDidNotSendReport(self, members):
        now = datetime.now()
        year = int(now.strftime("%Y"))
        didNotSendCount = members.count()
        message = ''
        if didNotSendCount > 0:
            message = '\n\n<b>&#128561; DID NOT SEND (' + str(didNotSendCount) + ') : </b> \n'
            message += self.generateBatchWiseDNSReport(members, year)
            message += self.generateBatchWiseDNSReport(members, year - 1)
            message += self.generateBatchWiseDNSReport(members, year - 2)
            message += self.generateBatchWiseDNSReport(members, year - 3)
        return message 
开发者ID:amfoss,项目名称:cms,代码行数:14,代码来源:StatusUpdateReporter.py

示例9: getLateReport

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def getLateReport(self, late_members):
        lateCount = late_members.count()
        message = ''
        if lateCount > 0:
            message += '\n\n<b>&#8987; LATE (' + str(lateCount) + ') : </b> \n\n'
            i = 0
            for member in late_members.all():
                i = i + 1
                timestamp = Message.objects.filter(thread=self.thread, member=member, date=self.date).order_by(
                    '-timestamp').first().timestamp
                message += str(i) + '. ' + self.getName(member) + ' [' + timestamp.astimezone(
                    timezone('Asia/Kolkata')).strftime('%I:%M %p') + '] \n'
        return message 
开发者ID:amfoss,项目名称:cms,代码行数:15,代码来源:StatusUpdateReporter.py

示例10: generateDailyReport

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def generateDailyReport(self):
        date = self.date
        thread = self.thread
        updates = Message.objects.filter(date=date, thread=thread).order_by('timestamp')
        first = UserProfile.objects.get(user=updates[0].member)
        last = UserProfile.objects.get(user=list(reversed(updates))[0].member)
        try:
            log = DailyLog.objects.get(date=date, thread=thread)
            allowKick = Thread.objects.get(name=thread).allowBotToKick

            totalMembers = log.members.count()
            didNotSendCount = log.didNotSend.count()
            invalidUpdatesCount = log.invalidUpdates.count()
            sendCount = totalMembers - (didNotSendCount + invalidUpdatesCount)

            message = '<b>Daily Status Update Report</b> \n\n &#128197; ' + date.strftime(
                '%d %B %Y') + ' | &#128228; ' + str(sendCount) + '/' + str(totalMembers) + ' Members'

            message += '\n\n<b>' + self.getPercentageSummary(sendCount, totalMembers) + '</b>'
            message += self.getInvalidUpdatesReport(log.invalidUpdates)
            if allowKick:
                message += self.getKickMembersReport(self.membersToBeKicked)
            if updates.count() > 0:
                message += '\n\n<b>&#11088; First : </b>' + first.first_name + ' ' + first.last_name + \
                           ' (' + updates[0].timestamp.astimezone(timezone('Asia/Kolkata')).strftime(
                    '%I:%M %p') + ')' + '\n'
                message += '<b>&#128012; Last : </b>' + last.first_name + ' ' + last.last_name + \
                           ' (' + list(reversed(updates))[0].timestamp.astimezone(timezone('Asia/Kolkata')).strftime(
                    '%I:%M %p') + ')' + '\n'
            message += self.generateDidNotSendReport(log.didNotSend)
            if thread.footerMessage:
                message += '\n<i>' + thread.footerMessage + '</i>'

            return message

        except ObjectDoesNotExist:
            raise 
开发者ID:amfoss,项目名称:cms,代码行数:39,代码来源:StatusUpdateReporter.py

示例11: _replace_bucket_placeholders

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def _replace_bucket_placeholders(self, name, date):
        name = name.replace('<year>', date.strftime('%Y'))
        name = name.replace('<month>', date.strftime('%m'))
        name = name.replace('<week>', date.strftime('%W'))
        return name 
开发者ID:indico,项目名称:indico-plugins,代码行数:7,代码来源:storage.py

示例12: date_to_str

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def date_to_str(date_str):
    return date.strftime('%Y-%m-%d') 
开发者ID:nmoya,项目名称:whatsapp-parser,代码行数:4,代码来源:datelib.py

示例13: date_to_weekday

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def date_to_weekday(date_str):
    if date_str.count("/") > 0:
        day, month, year = date_str.split("/")
        parsed_date = "%s-%s-%s" % (year, month, day)
        date_str = parsed_date

    # if year format is: 2012, 2000
    if len(year) == 4:
        return time.strftime("%A", time.strptime(date_str, "%Y-%d-%m"))
    # if year format is: 12, 00 
    return time.strftime("%A", time.strptime(date_str, "%y-%d-%m")) 
开发者ID:nmoya,项目名称:whatsapp-parser,代码行数:13,代码来源:datelib.py

示例14: add_scanid

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def add_scanid(self, id):
        for scanidpath in paths:
            self.scanidpath = paths['scanidpath'] + "scanID.txt"
        date = datetime.now()
        if os.path.isfile(self.scanidpath):
            file = open(self.scanidpath, "a")
            file.write(id + '\t' + date.strftime("%c") + '\n')
            file.close()
        else:
            file = open(self.scanidpath, "w")
            file.write('    Scan ID              Date      \n')
            file.write(id + '\t' + date.strftime("%c") + '\n')
            file.close() 
开发者ID:laincode,项目名称:shodan-seeker,代码行数:15,代码来源:shodanseeker.py

示例15: export_as_csv

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import strftime [as 别名]
def export_as_csv(self, filepath):
        just_size = 11
        csvfile = open(filepath, 'w')
        
        # Write the header
        csvfile.write(self.collection_info + "\n")
        csvfile.write("DATE,".ljust(just_size))
        for attribute in Record.attributes:
            attribute = attribute.upper() + ("," if attribute != Record.attributes[-1] else "") 
            csvfile.write(attribute.ljust(just_size))
        csvfile.write("\n")
        
        # Write each row
        for date, datum in self.data:
            csvfile.write((date.strftime(Record.date_format)+ ", ").ljust(just_size))
            
            for attribute in Record.attributes:
                if not attribute in datum:
                    raise Exception('Corrupted record data')
                
                if datum[attribute] is None:
                    text = "NA"
                else:
                    text = "%.3f" % datum[attribute]
                    
                if attribute != Record.attributes[-1]:
                    text += ", "
                    
                csvfile.write(text.ljust(just_size))
            csvfile.write("\n")
            
        print("\nSuccesfully written " + filepath + "!")
        csvfile.close() 
开发者ID:CorentinJ,项目名称:WeatherCollector,代码行数:35,代码来源:record.py


注:本文中的datetime.date.strftime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。