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

相关推荐

  1. Python: 获取时间

    2024-05-16 06:34:03       14 阅读
  2. mysql获取时间异常

    2024-05-16 06:34:03       40 阅读
  3. C# 时间获取

    2024-05-16 06:34:03       30 阅读
  4. vue3时间获取

    2024-05-16 06:34:03       48 阅读
  5. 如何获取时间戳?

    2024-05-16 06:34:03       35 阅读
  6. c#,获取时间

    2024-05-16 06:34:03       41 阅读
  7. 获取时间进行格式化

    2024-05-16 06:34:03       33 阅读
  8. redis获取过期时间

    2024-05-16 06:34:03       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-16 06:34:03       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-16 06:34:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-16 06:34:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-16 06:34:03       20 阅读

热门阅读

  1. 《图像处理的璀璨星空:技术演进与热点聚焦》

    2024-05-16 06:34:03       12 阅读
  2. Uniapp基础面试

    2024-05-16 06:34:03       15 阅读
  3. iOS 学习资料

    2024-05-16 06:34:03       14 阅读
  4. Rust语言实现图像编码转换

    2024-05-16 06:34:03       13 阅读
  5. DB类的学习

    2024-05-16 06:34:03       13 阅读
  6. 从HTTP迁移到HTTPS:一篇全面的测试方案设计指南

    2024-05-16 06:34:03       11 阅读
  7. MyBatis的一二级缓存区别

    2024-05-16 06:34:03       14 阅读
  8. http 和 https 的区别及原理解析

    2024-05-16 06:34:03       15 阅读
  9. 阅读笔记——《代码整洁之道》ch2

    2024-05-16 06:34:03       11 阅读