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()``【输出新的格式的时间字符串】

相关推荐
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python