Python 时间戳转换:使用 `time.strftime()` 将时间戳格式化为年月日时分秒
本文将介绍如何在 Python 中使用 time.strftime() 方法将时间戳转换为指定的日期时间格式,例如年月日时分秒。
示例代码:
import time
# 例子1: 将时间戳转换为'%Y-%m-%d %H:%M:%S'格式
timestamp = 1557502800
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
print(f'格式化后的时间:{formatted_time}')
# 例子2: 将时间戳转换为'%Y/%m/%d %H:%M:%S'格式
formatted_time = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(timestamp))
print(f'格式化后的时间:{formatted_time}')
# 例子3: 将时间戳转换为'%Y年%m月%d日 %H时%M分%S秒'格式
formatted_time = time.strftime('%Y年%m月%d日 %H时%M分%S秒', time.localtime(timestamp))
print(f'格式化后的时间:{formatted_time}')
输出结果:
格式化后的时间:2019-05-11 00:00:00
格式化后的时间:2019/05/11 00:00:00
格式化后的时间:2019年05月11日 00时00分00秒
解释:
time.strftime()方法用于将时间戳转换为指定的日期时间格式。'%Y-%m-%d %H:%M:%S'表示年-月-日 时:分:秒的格式。'%Y/%m/%d %H:%M:%S'表示年/月/日 时:分:秒的格式。'%Y年%m月%d日 %H时%M分%S秒'表示年月日 时分秒的格式。
通过使用 time.strftime() 方法,您可以轻松地将时间戳转换为各种日期时间格式。
原文地址: https://www.cveoy.top/t/topic/cQXl 著作权归作者所有。请勿转载和采集!