Python——模块

本文介绍了如何在Python中使用自定义模块`module_exercise.py`,展示了面向过程和面向对象的编程方法,并通过`time`模块实现日期相关功能,如计算星期和活了多少天。
摘要由CSDN通过智能技术生成

自定义模块

module_exercise.py文件

data =100
def func01():
    print("func01执行喽")
class Myclass:
    def func02(self):
        print("func02执行喽")
    @classmethod
    def func03(cls):
        print("func03执行喽")

exercise.py文件

# 调用方法1:"我过去"
#      --适用面向过程
import module_exercise
module_exercise.func01()
myclass = module_exercise.Myclass()
myclass.func02()
module_exercise.Myclass.func03()

# 调用方法2:"你过来"
#      --适用面向对象
from module_exercise import *
print(data)
func01()
myclass = Myclass()
myclass.func02()
Myclass.func03()

标准库模块

time模块

根据年月日计算星期
import time

tuple_week = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日",)


def get_week_name(year, month, day):
    """
        <根据年月日,计算星期>
    @param year: int 年
    @param month: int 月
    @param day: int 日
    @return: 例:星期二
    """
    time_str = f"{year}年{month}月{day}日"
    time_tuple = time.strptime(time_str, "%Y年%m月%d日")
    week_index = time_tuple[6]
    return tuple_week[week_index]


print(get_week_name(2024, 3, 14))

根据生日计算活了多天
def get_live_days(year, month, day):
    """
    @param year: int 年
    @param month: int 月
    @param day: int 日
    @return: int 活了几天
    """
    tuple_local_time = time.localtime()
    local_time_point = time.mktime(tuple_local_time)
    str_time = f"{year}-{month}-{day}"
    tuple_born_time = time.strptime(str_time, "%Y-%m-%d")
    born_time_point = time.mktime(tuple_born_time)
    live_senconds = local_time_point - born_time_point
    live_days = live_senconds / 60 / 60 // 24
    return f"从{year}年{month}月{day}日到现在总共活了{live_days}天"

print(get_live_days(2010, 1, 1))

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值