004python中时间类模块的总结time|datetime|calendar

004python中时间类模块的总结time|datetime|calendar

1.time|datetime|calendar基本语法

import time
import calendar
import datetime
# jupyter nbconvert --to markdown 1.ipynb,转化为md


def dt_time():
    """time用法介绍,主要用于时间的计算,格式化"""
    time_float = time.time()  # 1698557839.5913112,当前时间戳
    local_time = time.localtime(
        time_float)  # 时间格式对象 time.struct_time(tm_year=2023, tm_mon=10, tm_mday=29, tm_hour=13, tm_min=37, tm_sec=19, tm_wday=6, tm_yday=302, tm_isdst=0)
    ftime = time.asctime(local_time)  # 可读形式 Sun Oct 29 13:37:19 2023
    f1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()
                       )  # 格式化成2016-03-20 11:45:39形式
    # 格式化成Sat Mar 28 22:24:24 2016形式
    f2 = time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
    a = "Sat Mar 28 22:24:24 2016"
    a_time_struct = time.strptime(a,
                                  "%a %b %d %H:%M:%S %Y")  # 反格式化为对象 time.struct_time(tm_year=2016, tm_mon=3, tm_mday=28, tm_hour=22, tm_min=24, tm_sec=24, tm_wday=5, tm_yday=88, tm_isdst=-1)
    f3 = time.mktime(a_time_struct)  # 将格式字符串转换为时间戳,1459175064.0
    print(
        time_float,
        local_time,
        ftime,
        f1,
        f2,
        a_time_struct,
        f3,
        sep='\n'
    )


def dt_datetime():
    """datetime基本用法,主要用于日期的运算,有date,time,datetime,timedelta,tzinfo类"""
    print('date==' * 20)
    print("今天的日期是:", datetime.date.today())  # 今日的日期
    print("使用时间戳创建的日期:", datetime.date.fromtimestamp(1234567896))  # 使用时间戳创建日期
    print("使用公历序数创建的日期:", datetime.date.fromordinal(1))  # 使用公历序数创建的日期

    today = datetime.date(year=2023, month=12, day=31)  # 使用参数创建日期
    print('date对象的年份方式:', today.year, today.__getattribute__('year'))
    print('date对象的月份:', today.month, today.__getattribute__('month'))
    print('date对象的日:', today.day, today.__getattribute__('month'))

    # date大小比较方法
    # x.__eq__(y):x==y,ge:x>=y,gt:>,le:<=,lt:<,ne:!=
    d1 = datetime.date(2023, 1, 1)
    d2 = datetime.date(2023, 12, 3)
    print(d1.__eq__(d2))

    print("date对象的struct_time结构为:",  # 可以返回time对象
          today.timetuple())  # time.struct_time(tm_year=2020, tm_mon=8, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=244, tm_isdst=-1)
    print(today.timetuple().tm_year,
          today.timetuple().tm_mon, today.timetuple().tm_mday)

    d3 = d2.replace(2024, 3, 28)  # 替换为新的date,源不影响
    print(d2, d3)
    print("替换后的日期为:", today.replace(2019, 9, 29))
    print('date表示日期的最小单位:', datetime.date.resolution)

    print(
        time.time(),  # 当前时间戳,
        datetime.date.fromtimestamp(time.time()),  # 返回date对象
        datetime.date.max,  # 最大最小年月日
        datetime.date.min,
        today.__format__('%Y-%m-%d'),  # 指定格式格式化打印,下面等价
        today.strftime('%Y-%m-%d'),
        today.__str__(),
        today.ctime(),  # 返回一个表示日期的字符串(其格式如:Mon Aug 31 00:00:00 2020)
        sep='\n',
    )

    # 与fromordinal函数作用相反,元年00010101为1到现在的天数
    print("返回当前公历日期的序数:", today.toordinal())
    print("当前日期为星期(其中:周一对应0):{}".format(today.weekday()))  # 0周一
    print("当前日期为星期(其中:周一对应1):{}".format(
        today.isoweekday()))  # ISO标准的指定日期所在的星期数,1周一
    # datetime.IsoCalendarDate(year=2023, week=52, weekday=7)
    print("当前日期的年份、第几周、周几(其中返回为元组):", today.isocalendar())
    print("以ISO 8601格式'YYYY-MM-DD'返回date的字符串形式:",
          today.isoformat())  # ISO 8601标准 (YYYY-MM-DD)

    print('=time=' * 20)
    # x.__eq__(y)通用
    # time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
    create_time = datetime.time(hour=11, minute=18, second=31)  # 使用参数创建日期
    print('create_time对象的小时为:', create_time.hour,
          create_time.__getattribute__('hour'))
    print('create_time对象的分钟为:', create_time.minute)
    print('create_time对象的秒数为:', create_time.second)
    print("返回create_time的字符串形式:", create_time.isoformat())
    print("指定格式为:", create_time.strftime("%H/%M/%S"))
    print("替换后的时间为:", create_time.replace(20, 9, 29))

    print(
        # create_time.__nonzero__(),  # 时间对象是否非0
        datetime.time.max,  # 最大最小的时间
        datetime.time.min,
        datetime.time.resolution,  # 时间间隔单位
    )

    print('datetime==' * 20)
    # datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
    dt = datetime.datetime(2023, 12, 11, 13, 40, 14)  # 创建dt对象
    print(
        dt.time(),  # 返回时间,日期
        dt.date(),
        dt.utctimetuple(),  # 返回UTC时间元组
        datetime.datetime.strptime(
            '2024-3-28 19:55', '%Y-%m-%d %H:%M'),  # datetime对象
        datetime.datetime.utcfromtimestamp(time.time()),  # datetime对象
    )
    print("现在的时间是:", datetime.datetime.today())  # 2023-12-02 00:43:50.305469
    print("返回现在的时间是:", datetime.datetime.now())  # 2023-12-02 00:43:50.305469
    # 国际标准时间,2023-12-01 16:43:50.305469
    print("当前UTC日期和时间是:", datetime.datetime.utcnow())
    print("对应时间戳的日期和时间是:", datetime.datetime.fromtimestamp(
        1234567896))  # 2009-02-14 07:31:36
    print("对应UTC时间戳的日期和时间是:", datetime.datetime.utcfromtimestamp(
        1234567896))  # 2009-02-13 23:31:36
    print("公历序列对应的日期和时间是:", datetime.datetime.fromordinal(1))
    print("日期和时间的合体为:", datetime.datetime.combine(
        datetime.date(2020, 8, 31), datetime.time(12, 12, 12)))

    print('==timedelta==' * 15)
    # x.__sub__(y):x-y,x.__rsub__(y):y-x
    print(
        d1.__sub__(d2),
        sep='\n',
    )

    now = datetime.date.today()
    before_5_date = now + datetime.timedelta(days=-5)
    print("now date is:", now)  # 表示现在的日期
    print("before five days date is:", before_5_date)  # 表示五天前的日期
    now_time = datetime.datetime.now()  # 现在日期时间
    print(now_time)
    after_5_hours_10_minutes = now_time + \
        datetime.timedelta(hours=5, minutes=10)
    print(after_5_hours_10_minutes)

    date = datetime.datetime.strptime('2023-12-22', "%Y-%m-%d")  # 字符串创建日期对象
    print(date)


def dt_calendar():
    """calendar的基本用法,主要用于日历,年月日的计算"""
    cal: str = calendar.month(2016, 1)
    "以下输出2016年1月份的日历:"
    print(
        cal,  # 打印月历
        type(cal),
        calendar.calendar(2015, w=1, l=1, c=6),  # 打印日历,w左右天数间距,l天数上下间距,c月历左右间距
        calendar.isleap(2024),  # bool,是否是闰年
        calendar.leapdays(2010, 2033),  # 中间闰年个素数
        calendar.month(2023, 3, w=5, l=1),  # 打印月历,可以设置长宽
        calendar.monthrange(2023, 10),  # 返回第一天是星期几,该月有几天
        calendar.weekday(2023, 10, 29),  # 返回星期几
        sep='\n'
    )

    # 获取当前日期和时间
    now = datetime.datetime.now()
    # 获取当前月份的最后一天
    last_day_of_month = calendar.monthrange(now.year, now.month)[1]  # 返回当月有几天
    # 构造最后一天的日期对象
    last_day = datetime.datetime(now.year, now.month, last_day_of_month)
    # 打印结果
    print("当前日期和时间:", now)
    print("当月天数:", last_day_of_month)
    print("当前月份的最后一天:", last_day)


if __name__ == '__main__':
    dt_time()
    dt_datetime()
    dt_calendar()
1701453132.8771408
time.struct_time(tm_year=2023, tm_mon=12, tm_mday=2, tm_hour=1, tm_min=52, tm_sec=12, tm_wday=5, tm_yday=336, tm_isdst=0)
Sat Dec  2 01:52:12 2023
2023-12-02 01:52:12
Sat Dec 02 01:52:12 2023
time.struct_time(tm_year=2016, tm_mon=3, tm_mday=28, tm_hour=22, tm_min=24, tm_sec=24, tm_wday=5, tm_yday=88, tm_isdst=-1)
1459175064.0
date==date==date==date==date==date==date==date==date==date==date==date==date==date==date==date==date==date==date==date==
今天的日期是: 2023-12-02
使用时间戳创建的日期: 2009-02-14
使用公历序数创建的日期: 0001-01-01
date对象的年份方式: 2023 2023
date对象的月份: 12 12
date对象的日: 31 12
False
date对象的struct_time结构为: time.struct_time(tm_year=2023, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=365, tm_isdst=-1)
2023 12 31
2023-12-03 2024-03-28
替换后的日期为: 2019-09-29
date表示日期的最小单位: 1 day, 0:00:00
1701453132.87814
2023-12-02
9999-12-31
0001-01-01
2023-12-31
2023-12-31
2023-12-31
Sun Dec 31 00:00:00 2023
返回当前公历日期的序数: 738885
当前日期为星期(其中:周一对应0):6
当前日期为星期(其中:周一对应1):7
当前日期的年份、第几周、周几(其中返回为元组): datetime.IsoCalendarDate(year=2023, week=52, weekday=7)
以ISO 8601格式'YYYY-MM-DD'返回date的字符串形式: 2023-12-31
=time==time==time==time==time==time==time==time==time==time==time==time==time==time==time==time==time==time==time==time=
create_time对象的小时为: 11 11
create_time对象的分钟为: 18
create_time对象的秒数为: 31
返回create_time的字符串形式: 11:18:31
指定格式为: 11/18/31
替换后的时间为: 20:09:29
23:59:59.999999 00:00:00 0:00:00.000001
datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==datetime==
13:40:14 2023-12-11 time.struct_time(tm_year=2023, tm_mon=12, tm_mday=11, tm_hour=13, tm_min=40, tm_sec=14, tm_wday=0, tm_yday=345, tm_isdst=0) 2024-03-28 19:55:00 2023-12-01 17:52:12.878140
现在的时间是: 2023-12-02 01:52:12.878140
返回现在的时间是: 2023-12-02 01:52:12.878140
当前UTC日期和时间是: 2023-12-01 17:52:12.878140
对应时间戳的日期和时间是: 2009-02-14 07:31:36
对应UTC时间戳的日期和时间是: 2009-02-13 23:31:36
公历序列对应的日期和时间是: 0001-01-01 00:00:00
日期和时间的合体为: 2020-08-31 12:12:12
==timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta====timedelta==
-336 days, 0:00:00
now date is: 2023-12-02
before five days date is: 2023-11-27
2023-12-02 01:52:12.878140
2023-12-02 07:02:12.878140
2023-12-22 00:00:00
    January 2016
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

<class 'str'>
                                  2015

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                         1                         1
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       2  3  4  5  6  7  8
12 13 14 15 16 17 18       9 10 11 12 13 14 15       9 10 11 12 13 14 15
19 20 21 22 23 24 25      16 17 18 19 20 21 22      16 17 18 19 20 21 22
26 27 28 29 30 31         23 24 25 26 27 28         23 24 25 26 27 28 29
                                                    30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                   1  2  3       1  2  3  4  5  6  7
 6  7  8  9 10 11 12       4  5  6  7  8  9 10       8  9 10 11 12 13 14
13 14 15 16 17 18 19      11 12 13 14 15 16 17      15 16 17 18 19 20 21
20 21 22 23 24 25 26      18 19 20 21 22 23 24      22 23 24 25 26 27 28
27 28 29 30               25 26 27 28 29 30 31      29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                      1  2          1  2  3  4  5  6
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       7  8  9 10 11 12 13
13 14 15 16 17 18 19      10 11 12 13 14 15 16      14 15 16 17 18 19 20
20 21 22 23 24 25 26      17 18 19 20 21 22 23      21 22 23 24 25 26 27
27 28 29 30 31            24 25 26 27 28 29 30      28 29 30
                          31

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                         1          1  2  3  4  5  6
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       7  8  9 10 11 12 13
12 13 14 15 16 17 18       9 10 11 12 13 14 15      14 15 16 17 18 19 20
19 20 21 22 23 24 25      16 17 18 19 20 21 22      21 22 23 24 25 26 27
26 27 28 29 30 31         23 24 25 26 27 28 29      28 29 30 31
                          30

True
6
                March 2023
 Mon   Tue   Wed   Thu   Fri   Sat   Sun
               1     2     3     4     5
   6     7     8     9    10    11    12
  13    14    15    16    17    18    19
  20    21    22    23    24    25    26
  27    28    29    30    31

(6, 31)
6
当前日期和时间: 2023-12-02 01:52:12.878140
当月天数: 31
当前月份的最后一天: 2023-12-31 00:00:00
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值