时间模块

时间模块

  1. python中关于时间有三个模块:time、datetime(包括datetime、date)

  2. 获取时间戳

    import time
    timestamp_obj = time.time()    # 即可获取时间戳,是一串数字,
    # timestamp_obj = 1578545548.862143
    
  3. 将timestamp转为日期格式

    from datetime import date
    date_obj = date.fromtimestamp(timestamp_obj)
    # datetime.date(2020, 1, 9) 若print,为2020-01-09
    # 若不打印,得到的都是时间对象
    
  4. 获取当前时间

    # datetime模块 和 date模块均可以获取当前时间。推荐使用datetime模块
    from datetime import datetime, date
    print(date.today())     # 2020-01-09
    print(datetime.today())    # 2020-01-09 13:14:03.122298 不推荐使用
    print(datetime.now())    # 2020-01-09 13:14:35.033381
    # 三种方式都可以,使用功能datetime模块能够得到更准确的时间
    
  5. 转为struct_time格式,结构化格式时间

    date.today().timetuple()
    datetime.now().timetuple()
    # time.struct_time(tm_year=2020, tm_mon=1, tm_mday=9, tm_hour=13, tm_min=22, tm_sec=41, tm_wday=3, tm_yday=9, tm_isdst=-1)
    # 就是输出结构化的时间格式。date.today()得到的时间不准确,所以hour、min、sec等精确项,均为0.
    
  6. 替换当前时间

    date.today().replace(2015,3,2)
    # 就是简单的时间替换
    
  7. 将日期格式转为字符串

    datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # '2020-01-09 14:07:24'
    # strftime()中的参数(Y年,m月,d日,H小时,M分钟,S秒),只要在加上%即可,中间连接符号可以随意修改。得到的是一个字符串
    
  8. 将字符串转为时间格式

    datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
    # datetime模块的strptime()方法:接受两个参数(str,format)
    # 得到的是一个datetime对象,最好使用Y、m、d、H、M、S对应
    
from datetime import datetime

print(datetime.now())
# 2020-01-03 11:24:11.563112
print(datetime.now().today())
# 2020-01-03 11:24:11.563150
print(datetime.now().year)
# 2020
print(datetime.now().month)
# 1
print(datetime.now().day)
# 3
print(datetime.now().minute)
# 24
print(datetime.now().second)
# 11
原文地址:https://www.cnblogs.com/hui-code/p/12032256.html