Python 的 f-string 格式化时间和 strftime() 的区别是?

345 天前
 evemoo

就只是调用格式化的函数不同看起来更简洁一些?

print(f"Tick! The time is: {datetime.now():%Y-%m-%d %H:%M:%S}")

print(f"Tick! The time is: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
1056 次点击
所在节点    Python
2 条回复
kebyn
345 天前
官方文档上面讲了的,f-string 格式化时间和 strftime() 是一样的,date.__format__ Same as date.strftime()
https://docs.python.org/3/library/datetime.html#datetime.date.__format__
qianye216
345 天前
Python 的 f-string 和 strftime()都可以用来格式化时间,但两者有以下几点区别:

1. 语法不同:

- f-string: f"{time:%Y-%m-%d %H:%M}"
- strftime(): time.strftime("%Y-%m-%d %H:%M")

2. f-string 可以内嵌表达式,strftime()只接受格式字符串:

- f"{time:{format}}"
- strftime(format)

3. f-string 格式化发生在运行时,strftime 在调用时格式化

4. f-string 格式化只支持 datetime,strftime 可用于 datetime 和 time

5. f-string 从 Python 3.6 开始支持,strftime 存在于 2.x 和 3.x

6. f-string 使用{}包装表达式,strftime 使用%作为占位符

7. f-string 可以以内联的形式嵌入到字符串中,strftime 需要单独调用

8. f-string 由 Python 解析实现,strftime 由 C 语言实现,运行效率上会有差异

综上,主要区别在于语法方式,f-string 作为新特性更灵活,可内嵌表达式,但 strftime 可兼容 2.x,使用 C 实现,运行时效率较高。需要根据具体场景选择。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/959304

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX