一、datetime模块

import datetime


def test():
    curr_time = datetime.datetime.now() 
    print(f'当前时间为:{curr_time}')  # 2021-04-19 16:26:11.893965
    print(f'当前年份为:{curr_time.year}') # 2021
    print(f'当前月为:{curr_time.month}') # 4
    print(f'当前天为:{curr_time.day}') # 19
    print(f'当前时为:{curr_time.hour}') # 16
    print(f'当前分为:{curr_time.minute}') # 26
    print(f'当前秒为:{curr_time.second}') # 11
    print(f'当前日期为:{curr_time.date()}') # 2021-04-19


if __name__ == '__main__':
    test()
def test1():
    # datetime类型转为str类型
    curr_time = datetime.datetime.now()
    time_str = datetime.datetime.strftime(curr_time, '%Y-%m-%d %H:%M:%S')
    print(type(time_str))
    # str类型转为datetime类型
    time_datetime = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
    print(type(time_datetime))

二、time模块

import time


def test2():
    curr_tme = time.time()
    localtime = time.localtime(time.time())
    # 格式化时间
    format_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # 转化为时间戳
    timeStamp = time.mktime(localtime)
    print(f'当前时间的时间戳为:{curr_tme}') # 1618821684.9919617
    print(f'本地时间为为:{localtime}') # time.struct_time(tm_year=2021, tm_mon=4, tm_mday=19, tm_hour=16, tm_min=41, tm_sec=24, tm_wday=0, tm_yday=109, tm_isdst=0)
    print(f'格式化后时间为:{format_time}') # 2021-04-19 16:41:24
    print(f'转化后时间戳为:{timeStamp}') # 1618821684.0

Q.E.D.


Nothing really matters to me!