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

相关推荐
m0_748554811 小时前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
smj2302_796826522 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
阿正呀3 小时前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
九转成圣3 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
SmartRadio3 小时前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
2501_901200533 小时前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
laowangpython3 小时前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫3 小时前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch3 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI3 小时前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn