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

相关推荐
点云-激光雷达-Slam-三维牙齿2 小时前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐63 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
从零开始学习人工智能9 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
WWJA王文举10 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
卷无止境10 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131410 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教10 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教11 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境11 小时前
FastAPI 的Admin面板生态
后端·python
qq_4480111611 小时前
C语言中的动态内存分配
c语言·开发语言·php