python的时间模块time和datetime模块

time的基本使用

import time

now = time.time()
print(int(now))
now_tuple = time.localtime(now)
print(now_tuple)
time.sleep(1)
# 格式化
now_str = time.strftime("%Y-%m-%d %H:%M:%S %p", now_tuple)
print(now_str)
now_str1 = time.strftime("%Y-%m-%d %H:%M:%S %p")
print(now_str1)
now_str1 = time.strftime("%y-%m-%d")  # 显示年后两位
print(now_str1)
now_str1 = time.strftime("%Y-%m-%d")
print(now_str1)
# 英文显示
print(time.asctime(now_tuple))

# 将时间元组转化为时间戳
time_tuple = (2022, 4, 30, 16, 9, 33, 0, 0, 0)
print(time.mktime(time_tuple))

运行结果:

datetime的基础使用

import datetime

# 获取当前时间
print(datetime.datetime.today())
print(datetime.datetime.now())
# 获取当前时间戳now()和today()都可以
now = datetime.datetime.today().timestamp()
print(now)

# 将时间戳转化为时间
nowt = 1651306496
t = datetime.datetime.fromtimestamp(nowt)
print(t)

# 自定义格式化时间
jason = datetime.datetime.now()
now_str = jason.strftime("%Y-%m-%d %H:%M:%S %p")
print(now_str)

运行结果:

posted @ 2022-04-30 16:27  jasonchenYT  阅读(36)  评论(0编辑  收藏  举报