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

相关推荐
2601_9622982740 分钟前
Python自动化脚本的编写01
python·appium·自动化脚本·web自动化·应收账款管理
AIFQuant1 小时前
Python实时外汇行情接入实战:WebSocket与REST K线查询
开发语言·python·websocket
babe小鑫1 小时前
生物统计学专业校招:SAS、R、Python学习顺序实用指南
python·学习·r语言
vx_Biye_Design1 小时前
springboot游泳馆系统93765-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·spring·课程设计
固定资产管理系统软件2 小时前
该去哪里找专业靠谱的智慧智能设备固定资产管理系统?
人工智能·python
ctlover2 小时前
LangChain 概述
python·langchain
专业程序开发源2 小时前
springbootLivehouse票务系统-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·pygame
李高钢2 小时前
Python Django 框架入门:从零搭建你的第一个 Web 应用
前端·python·django
2601_966949652 小时前
从轮询到策略消费:量化系统如何高效处理五档盘口数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
萧鼎2 小时前
2026实战:用 accelerate 库加速 PyTorch 训练,核心语法与避坑指南
python·开源·教程·python库·accelerate