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

相关推荐
创世宇图13 分钟前
【Python工程化实战】Kubernetes 中 Python 应用的优雅启停与健康检查:零停机滚动更新实战
python·云原生·kubernetes·优雅停机
zhiSiBuYu05171 小时前
重排序(Rerank)提升检索准确率实战指南
开发语言·python·算法
MageGojo1 小时前
集成企业工商信息查询API:从在线调试到生产级调用实战
python·调试·rest api·api集成·企业信息查询
huangjiazhi_1 小时前
Python3.14编写文件服务器
python
郭梧悠1 小时前
算法:有效的括号
python·算法·leetcode
佛珠散了一地1 小时前
ONNX Runtime GPU 推理配置指南
python
派葛穆2 小时前
Python-pip切换镜像源
开发语言·python·pip
CTA终结者2 小时前
2026年AI量化提效,工具重点要按阶段调整
人工智能·python
xxie1237942 小时前
Python 闭包:函数嵌套的 “状态捕获” 机制
开发语言·python
c_lb72883 小时前
最新AI量化提效,交易认知和技术实现要接上
人工智能·python