python封装当前日期时间函数

该代码示例展示了如何利用Python的os、datetime和date库获取当前日期和时间,并创建一个以当前日期为名的文件路径。通过date.today()获取日期,datetime.now().strftime()格式化获取当前时间,os.path.join()和os.makedirs()创建文件路径及多级目录。
摘要由CSDN通过智能技术生成

通过os、date、datetime库获取当前日期、时间、文件创建路径

import os
from datetime import datetime, date
class DateTime(object):
    @staticmethod
    def get_current_date():
        """获取当前日期"""
        try:
            current_date = date.today()
        except Exception as e:
            raise e
        else:
            return str(current_date)

    @staticmethod
    def get_current_time():
        """获取当前时间"""
        try:
            time = datetime.now()
            current_time = time.strftime('%H_%M_%S')
        except Exception as e:
            raise e
        else:
            return current_time

    @staticmethod
    def create_file_path():
        """创建文件存放路径路径"""
        try:
            file_path = os.path.join("文件路径", DateTime.get_current_date())
            if not os.path.exists(file_path):
                os.makedirs(file_path)  # 生成多级目录
        except Exception as e:
            raise e
        else:
            return file_path

if __name__ == '__main__':
    print(DateTime.get_current_date())
    print(DateTime.get_current_time())
    print(DateTime.create_file_path())

运行结果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值