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

相关推荐
min(a,b)23 分钟前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
yangshicong2 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华2 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb72882 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
chenment4 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
IT空门:门主4 小时前
Python 基础语法学习路线图
网络·python·学习
互联网中的一颗神经元5 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql
RSTJ_16256 小时前
PYTHON+AI LLM DAY ONE HUNDRED AND EIGHTEEN
python
开源量化GO6 小时前
近期量化学习路径,交易理解和技术实现要接上
人工智能·python
c_lb72887 小时前
近期手工规则量化,学习表达到开发验证要连起来
人工智能·python