Python 获取本地时间与时间戳转换实战
在 Python 开发中,处理时间数据是常见需求。本文演示如何利用内置的 time 模块获取本地时间,并实现时间戳与日期字符串之间的相互转换。
获取本地时间与格式化
Python 的 time 模块提供了获取当前时间的功能。使用 time.localtime() 可以获取一个包含年、月、日、时、分、秒等信息的结构化时间对象(struct_time)。若需将其转换为易读的字符串格式,可结合 time.strftime() 函数,指定如 '%Y-%m-%d %H:%M:%S' 这样的格式符。
import time
# 获取当前本地时间对象
now = time.localtime()
# 格式化为字符串:年-月-日 时:分:秒
now_str = time.strftime('%Y-%m-%d %H:%M:%S', now)时间戳的获取与转换
时间戳通常指从 1970 年 1 月 1 日 00:00:00 到当前时间的秒数。在 Python 中,time.time() 直接返回当前时间的时间戳(浮点数)。要将格式化后的日期字符串转换回时间戳,需先通过 time.strptime() 将字符串解析为 struct_time 对象,再使用 time.mktime() 将其转换为时间戳。
# 获取当前时间戳
now_stamp = time.time()
# 日期字符串转时间戳
# 注意:需确保字符串格式与 strptime 中的格式一致
timestamp_from_str = time.mktime(time.strptime(now_str, "%Y-%m-%d %H:%M:%S"))
# 时间戳转日期字符串
date_from_stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_stamp))完整示例代码
以下代码整合了上述操作,展示从获取本地时间到各种格式转换的完整流程:
import time
# 1. 获取当前时间对象
now = time.localtime()
# 2. 格式化为日期字符串
now_str = time.strftime('%Y-%m-%d %H:%M:%S', now)
# 3. 获取当前时间戳
now_stamp = time.time()
# 4. 日期字符串转时间戳
change_to_stamp = time.mktime(time.strptime(now_str, "%Y-%m-%d %H:%M:%S"))
# 5. 时间戳转日期字符串
change_to_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_stamp))
# 输出结果验证
print("本地时间对象:", now)
print("格式化日期:", now_str)
print("当前时间戳:", now_stamp)
print("字符串转时间戳:", change_to_stamp)
print("时间戳转日期:", change_to_time)
总结
通过 time 模块,开发者可以灵活地在 struct_time、时间戳和格式化字符串之间进行转换。掌握 localtime、strftime、mktime 和 strptime 的配合使用,能有效解决日志处理、文件命名及数据序列化中的时间格式问题。以上就是基于 Python 获取本地时间并转换时间戳和日期格式的详细内容,更多关于 Python 时间处理技巧的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













