Python 时间戳转年月日格式:f字符串与 strftime 函数
在 Python 中,可以使用 f 字符串和 datetime 模块中的 strftime 函数来将指定的时间戳改为年月日的格式。下面是一些例子:
- 将当前时间戳格式化为年月日的字符串:
from datetime import datetime
timestamp = datetime.now().timestamp()
formatted_date = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d')
print(f'The formatted date is: {formatted_date}')
- 将给定的时间戳格式化为年月日的字符串:
from datetime import datetime
timestamp = 1620352372 # 2021-05-07 16:32:52
formatted_date = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d')
print(f'The formatted date is: {formatted_date}')
- 将时间戳作为变量,并格式化为年月日的字符串:
from datetime import datetime
timestamp = 1620352372 # 2021-05-07 16:32:52
formatted_date = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d')
print(f'The formatted date is: {formatted_date}')
message = f'The date is: {formatted_date}'
print(message)
输出结果:
The formatted date is: 2021-05-07
The date is: 2021-05-07
在上述例子中,我们使用 strftime 函数将时间戳格式化为年月日的字符串,其中 %Y 表示四位数的年份,%m 表示两位数的月份,%d 表示两位数的日期。
原文地址: https://www.cveoy.top/t/topic/cQ1i 著作权归作者所有。请勿转载和采集!