Python: 获取时间

python 复制代码
from datetime import datetime, timedelta

# 获取当前时间
current_time = datetime.now()
print(f"current_time = {current_time}")

# 获取时分秒部分
time = current_time.time()
print(f"time = {time}")

# 获取当前时间,只要日期部分
current_date = current_time.date()
print(f"current_date = {current_date}")

# 获取前一天
previous_date = current_date - timedelta(days=1)
print(f"previous_date = {previous_date}")

# 获取上个月的最后一天
last_month_end_date = current_date - timedelta(days=current_date.day)
print(f"last_month_end_date = {last_month_end_date}")

# 获取上个季度的最后一天
# 当前季度
quarter = (current_date.month - 1) // 3 + 1
# 当前季度起始月份
quarter_start_month = quarter * 3 - 2
# 当前季度起始日期
quarter_start_date = datetime.strptime(str(current_date.year) + "-" + str(quarter_start_month) + "-1",'%Y-%m-%d')
# 上个季度最后一天
last_quarter_end_date = quarter_start_date + timedelta(days = -1)
print(f"last_quarter_end_date = {last_quarter_end_date}")

运行结果:

current_time = 2024-05-10 13:14:14.906362

time = 13:14:14.906362

current_date = 2024-05-10

previous_date = 2024-05-09

last_month_end_date = 2024-04-30

last_quarter_end_date = 2024-03-31 00:00:00

相关推荐
好家伙VCC6 分钟前
**CQRS模式实战:用Go语言构建高并发读写分离架构**在现代分布式系统中,随着业务复杂度的提升和用户量的增长,传统的单数据库模型逐
java·数据库·python·架构·golang
fy121636 分钟前
Java进阶——IO 流
java·开发语言·python
flyfox9 分钟前
OpenClaw(龙虾) Skills 实战开发指南
人工智能·python·源码
深藏功yu名30 分钟前
Day27:LangGraph 实战落地|Tool_RAG + 并行子图 + 持久化部署,打造工业级 AI Agent
人工智能·python·ai·pycharm·rag·langgrap
reasonsummer1 小时前
【办公类-142-04】20260330插班生word转长表EXCLE(4)新表重制
python·word
曲幽1 小时前
FastAPI + Celery 实战:异步任务里调用 Redis 和数据库的全解析,及生产级组织方案
redis·python·fastapi·web·async·celery·task·queue
程序员三藏1 小时前
软件测试:白盒测试详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
青梅煮酒与君饮1 小时前
浅谈大模型、Agent、Function Calling、MCP、Skill、Subagent、Langchain、Workflow
人工智能·python·语言模型·langchain·llama