• Python日期和时间库datetime


    简介

    datetime:处理日期和时间

    calendar:处理日历

    time:时间的访问和转换

    dateutil:扩展时区和解析支持的第三方库




    初试

    import time
    
    print(time.strftime("%Y-%m-%d %H:%M:%S"))  # 2020-07-16 13:58:27
    
    • 1
    • 2
    • 3

    可以简单为

    import datetime
    
    print(datetime.date.today())  # 日期
    print(datetime.datetime.now())  # 日期+时间
    # 2020-07-16
    # 2020-07-16 13:58:27.161542
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6




    有效类型

    描述
    date日期,年月日
    time时间,时分秒毫秒时区
    datetime日期+时间
    timedelta时间间隔
    tzinfo时区
    timezone相对于UTC(世界标准时间)的偏移量

    关系

    object
        timedelta
        tzinfo
            timezone
        time
        date
            datetime
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7




    星期几

    调用datetime.weekday()datetime.isoweekday()

    from datetime import datetime
    
    print(datetime.now().weekday())  # 周一为0,周日为6
    print(datetime.now().isoweekday())  # 周一为1,周日为7
    
    • 1
    • 2
    • 3
    • 4




    日期相差时间

    利用 datetime.timedelta 的方法 total_seconds() 获取时间间隔包含了多少秒

    计算2020年春节放几天假

    from datetime import date, timedelta
    
    date1 = date(2020, 1, 24)  # 开始放假
    date2 = date(2020, 2, 2+1)  # 开始上班
    delta = date2 - date1
    print(delta)
    print(delta.total_seconds())
    # 10 days, 0:00:00
    # 864000.0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9




    加减时间

    利用 datetime.timedelta

    from datetime import datetime, timedelta
    
    now = datetime.now()
    after_a_week = now + timedelta(days=7)
    print(now)  # 2021-04-15 17:55:58.794208
    print(after_a_week)  # 2021-04-22 17:55:58.794208
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6




    字符串转时间

    Python 3.7 以上

    from datetime import datetime
    
    date_string = '2021-04-19 18:18:39.458818'
    print(datetime.fromisoformat(date_string))
    
    • 1
    • 2
    • 3
    • 4

    Python 3.7 以下

    from datetime import datetime
    
    
    def fromisoformat(date_string):
        """datetime字符串转datetime"""
        return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
    
    
    date_string = '2021-04-19 18:18:39.458818'
    print(fromisoformat(date_string))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10




    时间转字符串(时间作为文件名)

    文件名不可以有冒号 :

    import locale
    import datetime
    
    locale.setlocale(locale.LC_CTYPE, 'Chinese')  # 设置语言环境
    print(datetime.datetime.now())
    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print(datetime.datetime.now().strftime('%Y/%m/%d'))
    print(datetime.datetime.now().strftime('%Y年%m月%d日'))
    print(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
    print(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
    print(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S_%f'))
    # 2023-04-19 10:19:36.479925
    # 2023-04-19 10:19:36
    # 2023/04/19
    # 2023年04月19日
    # 20230419101936
    # 20230419_101936
    # 2023-04-19_10-19-36_480925
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    详细查阅 Format Codes

    在 Linux 上可能会报错:locale.Error: unsupported locale setting

    用这种

    import datetime
    
    now = datetime.datetime.now()
    print(now.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日'))
    
    • 1
    • 2
    • 3
    • 4




    与时间戳互转

    import datetime
    
    print(datetime.datetime(2021, 12, 7).timestamp())  # 1638806400.0
    print(datetime.datetime.fromtimestamp(1638806400))  # 2021-12-07 00:00:00
    
    • 1
    • 2
    • 3
    • 4




    参考文献

    1. datetime — 基本的日期和时间类型
    2. Python时间访问和转换库time,含时间戳和时间互转
  • 相关阅读:
    redis能否替代threadlocal
    canvas基础4 -- 图像
    LeetCode_各种排序算法和查找算法
    json转换
    070:mapboxGL加载含有shp文件的zip,显示图形
    包装类与基本类型的区别
    进制和位运算
    猿如意开发工具|JetBrains GoLand
    Windows 安装 RabbitMq
    ubuntu 20.04+ORB_SLAM3 安装并行全记录(无坑版)(一)
  • 原文地址:https://blog.csdn.net/lly1122334/article/details/106680887