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

相关推荐
databook15 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室15 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三17 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271120 小时前
Python之语言特点
python
刘立军21 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python