Python 中的strftime()函数

一、简介
在 Python 中,strftime() 函数用于将时间转换为指定格式的字符串。它是一种强大且灵活的工具,可以将时间按照我们需求的格式显示出来。在本文中,我们将详细讨论 strftime() 函数的使用方法和常见的格式化代码。
二、strftime() 函数的基本用法
strftime() 函数属于 datetime 模块,用于将日期与时间格式化为字符串。该函数的语法如下:
strftime(format)
其中,format 参数是一个字符串,用于指定输出的格式。下面是一些常见的格式化代码及其对应的含义。
| 格式化代码 | 含义 | 示例 |
|---|---|---|
| %Y | 年份,包括世纪(如 2019) | 2022 |
| %y | 年份,不包括世纪(如 19) | 22 |
| %m | 月份(01~12) | 03 |
| %B | 月份的全称,如 January | March |
| %b | 月份的缩写,如 Jan | Mar |
| %d | 日期(01~31) | 08 |
| %A | 星期的全称,如 Sunday | Wednesday |
| %a | 星期的缩写,如 Sun | Wed |
| %H | 小时(24小时制,00~23) | 14 |
| %I | 小时(12小时制,01~12) | 06 |
| %p | AM 或 PM | PM |
| %M | 分钟(00~59) | 23 |
| %S | 秒数(00~59) | 45 |
| %f | 微秒(000000~999999) | 601000 |
| %Z | 时区名称,如 UTC,EST | CST |
| %j | 年份中的第几天(001~366) | 256 |
| %U | 每年的第几周,周日为每周的第一天(00~53) | 35 |
| %W | 每年的第几周,周一为每周的第一天(00~53) | 34 |
三、示例演示
下面,我们将通过一些示例来演示 strftime() 函数的基本用法。首先,我们需要导入 datetime 模块。
import datetime
1. 将当前时间转换为字符串
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
运行结果:
2022-03-08 14:23:45
2. 将指定的时间转换为字符串
specified_time = datetime.datetime(2022, 3, 8, 16, 30, 0)
formatted_time = specified_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
运行结果:
2022-03-08 16:30:00
3. 获取时间相关信息的字符串
current_time = datetime.datetime.now()
year = current_time.strftime("%Y")
month = current_time.strftime("%B")
day = current_time.strftime("%A")
print("Year:", year)
print("Month:", month)
print("Day:", day)
运行结果:
Year: 2022
Month: March
Day: Wednesday
4. 其他格式化示例
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y/%m/%d %H:%M:%S %p")
print(formatted_time)
formatted_time = current_time.strftime("%Y-%m-%d %I:%M:%S %p")
print(formatted_time)
运行结果:
2022/03/08 14:23:45 PM
2022-03-08 02:23:45 PM
四、自定义格式化代码
除了上述常见的格式化代码,strftime() 函数还支持一些自定义的格式化代码。
1. %x 和 %X
% x 用于表示日期,% X 用于表示时间。它们的输出格式会有所不同,具体取决于系统的设置。
current_time = datetime.datetime.now()
formatted_date = current_time.strftime("%x")
formatted_time = current_time.strftime("%X")
print(formatted_date)
print(formatted_time)
运行结果:
03/08/22
14:23:45
2. %c
%c 会根据系统的设置,输出日期和时间的字符串表示。
current_time = datetime.datetime.now()
formatted_datetime = current_time.strftime("%c")
print(formatted_datetime)
运行结果:
Wed Mar 8 14:23:45 2022
五、总结
在本文中,我们详细讨论了 Python 中 strftime() 函数的用法。我们学习了 strftime() 函数的基本语法,并演示了一些示例来说明其用法。同时,我们也提到了一些常见的格式化代码和一些自定义的格式化代码。strftime() 函数提供了灵活的日期和时间格式化功能,能够满足我们在项目中对时间表达的各种需求。
极客教程