• Python 入门之 内置模块 -- datetime模块


    1、datetime模块

    from datetime import datetime
    

    (1)datetime.now() 获取当前时间和日期

    print(datetime.now())   # 获取当前时间
    

    (2)获取指定时间和日期

    dt = datetime(2018,5,20,13,14)
    print(dt)
    

    (3)指定时间

    current_time = datetime.datetime.now()
    print(current_time.replace(year=1977))                  # 直接调整到1977年
    print(current_time.replace(month=1))                    # 直接调整到1月份
    print(current_time.replace(year=1989,month=4,day=25))   # 1989-04-25 18:49:05.898601
    

    (4)求时间差

    print(datetime(2018,10,1,10,11,12) - datetime(2011,11,1,20,10,10))
    

    (5)datetime.timestamp() 将对象转换成时间戳

    d = datetime.now()
    print(d.timestamp())
    

    (6)datetime.fromtimestamp() 将时间戳转换为对象

    import time
    
    f_t = time.time()
    print(datetime.fromtimestamp(f_t))
    

    (7)datetime.strftime 将对象转换成字符串

    d = datetime.now()
    print(d.strftime("%Y-%m-%d %H:%M:%S"))
    

    (8)datetime.strptime 将字符串转换成对象

    s = "2018-12-31 10:11:12"
    print(datetime.strptime(s,"%Y-%m-%d %H:%M:%S"))
    

    (9)可以进行加减运算

    from datetime import datetime,timedelta
    
    print(datetime.now() - timedelta(days=1))
    print(datetime.now() - timedelta(hours=1))
    
  • 相关阅读:
    幸福之路
    mysql8.0.25安装配置教程(windows 64位)
    解决git@gitee.com: Permission denied (publickey).
    python路径拼接os.path.join()函数的用法
    如何正确的看待Python里的GIL锁
    安装激活Golang
    Django的Orm操作数据库
    爬虫技术栈点
    Django
    Python/数据库/Django笔记
  • 原文地址:https://www.cnblogs.com/caiyongliang/p/11490818.html
Copyright © 2020-2023  润新知