当前位置: 首页 > article >正文

Python 时间日期模块编码模板(时间日期对象基本操作、时间日期对象格式化与解析)

一、时间日期对象基本操作

1、获取当前时间日期对象
import datetime

current_datetime = datetime.datetime.now()

print(current_datetime)
# 输出结果

2024-10-05 21:00:53.224413
2、创建时间日期对象
import datetime

my_datetime = datetime.datetime(2023, 1, 1, 12, 0, 0)

print(my_datetime)
# 输出结果

2023-01-01 12:00:00
3、时间日期对象的属性
import datetime

my_datetime = datetime.datetime(2023, 1, 1, 12, 0, 0)

print(my_datetime.year)
print(my_datetime.month)
print(my_datetime.day)
print(my_datetime.hour)
print(my_datetime.minute)
print(my_datetime.second)
# 输出结果

2023
1
1
12
0
0
4、时间日期对象的运算
import datetime

my_datetime = datetime.datetime(2023, 1, 1, 12, 0, 0)

one_day_later = my_datetime + datetime.timedelta(days=1)

print(one_day_later)

one_hour_earlier = my_datetime - datetime.timedelta(hours=1)

print(one_hour_earlier)
# 输出结果

2023-01-02 12:00:00
2023-01-01 11:00:00

二、时间日期对象格式化与解析

1、时间日期对象格式化
import datetime

my_datetime = datetime.datetime(2023, 1, 1, 12, 0, 0)

str1 = my_datetime.strftime("%Y 年 %m 月 %d 日 %H 时 %M 分 %S 秒")
str2 = my_datetime.strftime("%Y 年 %m 月 %d 日")
str3 = my_datetime.strftime("%H 时 %M 分 %S 秒")

print(str1)
print(str2)
print(str3)
# 输出结果

2023 年 01 月 01 日 12 时 00 分 00 秒
2023 年 01 月 01 日
12 时 00 分 00 秒
2、字符串解析为时间日期对象
import datetime

str = "2023 年 01 月 01 日 12 时 00 分 00 秒"

my_datetime = datetime.datetime.strptime(str, "%Y 年 %m 月 %d 日 %H 时 %M 分 %S 秒")

print(my_datetime)
# 输出结果

2023-01-01 12:00:00

http://www.kler.cn/news/335353.html

相关文章:

  • Java语法-类和对象之抽象类和接口
  • node启动websocket保持后台一直运行
  • Linux命令:用于管理 Linux 系统中用户组的命令行工具gpasswd详解
  • 【深度学习】—线性回归 线性回归的基本元素 线性模型 损失函数 解析解 随机梯度下降
  • kaggle实战3RossmanStore商店销售额预测XgBoost解决回归问题案例1
  • 在 Ubuntu 安装 Python3.7(没有弯路)
  • Qt之TCP收发图片的例子
  • 大模型生成时的参数设置怎么调整?
  • 9--苍穹外卖-SpringBoot项目中Redis的介绍及其使用实例 详解
  • 男单新老对决:林诗栋VS马龙,巅峰之战
  • 【优选算法】(第十二篇)
  • 8647 实现图的存储结构
  • 数据结构与算法——Java实现 30.合并多个有序链表 小顶堆实现
  • 微信朋友圈实况照片需要注意隐私
  • 独立站如何批量查收录,独立站批量查询收录的操作方法
  • MongoDB入门:安装及环境变量配置
  • (刷题记录5)盛最多水的容器
  • “衣依”服装销售平台:Spring Boot技术架构剖析
  • leetcode99 恢复二叉搜索树
  • 基于微信小程序的健康管理系统(源码+定制+文档)