當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。