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

相关推荐
傻啦嘿哟5 分钟前
Python操作Redis:高效缓存设计与实战
redis·python·缓存
Fairy要carry9 分钟前
面试-Agent任务编排怎么处理?
网络·python·面试
EW Frontier24 分钟前
【UAV识别】基于分层学习的射频无人机检测与识别技术,准确率达99%!【附python代码】
python·无人机·无人机信号识别
WangYaolove131431 分钟前
基于循环神经网络的情感分类(源码+文档)
python·mysql·django·毕业设计·源码
badhope32 分钟前
GitHub超有用项目推荐:skill仓库--用技能树打造AI超频引擎
java·开发语言·前端·人工智能·python·重构·github
进击的小头40 分钟前
第12篇:开环系统伯德图设计控制器
python·算法
t_hj40 分钟前
腾讯QClaw深度试用:一句话创建专业级网络爬虫
开发语言·python
asdzx671 小时前
使用 Python 比较 PDF 文件差异(简单方法)
python·pdf·文档比较
穿过锁扣的风1 小时前
【完整带注释版】图像直方图绘制教程(OpenCV+Matplotlib)
笔记·python·opencv
zyq99101_11 小时前
蓝桥杯刷题算法实战解析
数据结构·python·算法·蓝桥杯