Python time strptime()和strftime()

1 strptime()方法

根据指定的格式把一个时间字符串解析为时间元组

重要的时间日期格式化符号

%y 两位数的年份表示(00-99)

%Y 四位数的年份表示(000-9999)

%m 月份(01-12)

%d 月内中的一天(0-31)

%H 24小时制小时数(0-23)

%I 12小时制小时数(01-12)

%M 分钟数(00-59)

%S 秒(00-59)

%j 年内的一天(001-366)【DOY】

复制代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import time
 
struct_time = time.strptime("2023 11 02", "%Y %m %d")
print(struct_time)
# 得到结果:
# time.struct_time(tm_year=2023, tm_mon=11, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=306, tm_isdst=-1)

2 strftime()方法

格式化时间,返回新的格式的字符串,格式由参数format决定

复制代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%Y-%m-%d, %H:%M:%S")
print("date and time:",date_time)

3 总结

1 首先从数据中提取时间字符串

2 利用函数strptime()将时间字符串转换为time类型数据

3 利用该time类型数据进行【日期的提取】

4 或者利用函数`strftime()``【输出新的格式的时间字符串】

相关推荐
用户8356290780514 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780514 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生12 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师13 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码13 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf13 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python