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

相关推荐
cnxy1887 小时前
围棋对弈Python程序开发完整指南:步骤4 - 提子逻辑和劫争规则实现
开发语言·python·机器学习
TheSumSt8 小时前
Python丨课程笔记Part3:语法进阶部分(控制结构与基础数据结构)
数据结构·笔记·python
ha_lydms8 小时前
5、Spark函数_s/t
java·大数据·python·spark·数据处理·maxcompute·spark 函数
电商API&Tina9 小时前
跨境电商 API 对接指南:亚马逊 + 速卖通接口调用全流程
大数据·服务器·数据库·python·算法·json·图搜索算法
Yyyyy123jsjs9 小时前
外汇Tick数据交易时段详解与Python实战分析
人工智能·python·区块链
默默前行的虫虫9 小时前
nicegui地图总结
网络·python
不易思不逸10 小时前
SAM2 测试
人工智能·python
趣知岛11 小时前
智能家居与物联网项目实战全指南:从架构设计到落地部署
python·物联网·智能家居
龘龍龙12 小时前
Python基础(八)
开发语言·python
vibag13 小时前
FastAPI框架
python·pycharm·fastapi