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

相关推荐
weixin_468466851 天前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题
Nina_7171 天前
pytorch核心组件以及流程
人工智能·pytorch·python
Highcharts.js1 天前
在Python中配置高度交互的数据可视化:Highcharts完全指南
开发语言·python·信息可视化·highcharts
Ace_31750887761 天前
京东关键字搜索接口逆向:从动态签名破解到分布式请求调度
分布式·python
yachuan_qiao1 天前
专业的建筑设备监控管理系统选哪家
大数据·运维·python
l1t1 天前
DeepSeek辅助编写转换DuckDB json格式执行计划到PostgreSQL格式的Python程序
数据库·python·postgresql·json·执行计划
q***82911 天前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
李昊哲小课1 天前
cuda12 cudnn9 tensorflow 显卡加速
人工智能·python·深度学习·机器学习·tensorflow
FreeCode1 天前
LangChain1.0智能体开发:检索增强生成(RAG)
python·langchain·agent
xixixi777771 天前
攻击链重构的具体实现思路和分析报告
开发语言·python·安全·工具·攻击链