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 @   jasonchenYT  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示