登录
首页 >  文章 >  python教程

time与datetime模块转换方法解析

时间:2026-04-05 08:10:11 115浏览 收藏

Python中time模块与datetime模块虽都用于时间处理,但设计思路迥异:前者基于时间戳和struct_time结构,后者采用面向对象方式,更直观易用;二者转换的核心在于时间戳这一“桥梁”——struct_time可通过time.mktime转为时间戳再用datetime.fromtimestamp转为datetime对象,而datetime对象则能通过timestamp()或timetuple()方法反向生成时间戳或struct_time,掌握这一互转逻辑,能显著提升时间数据处理的灵活性与效率。

python中time与datetime模块如何转换?

在Python中,timedatetime 模块都用于处理时间,但它们的数据类型和使用方式略有不同。掌握它们之间的转换方法,有助于灵活处理时间数据。

time模块与datetime模块简介

time 模块主要基于时间戳(timestamp)操作,常用函数如 time.time()time.localtime() 返回的是 struct_time 对象。
datetime 模块更面向对象,常用类有 datetime.datetime,使用起来更直观。

从time转换为datetime

如果你有一个 time.struct_time 或时间戳,可以转为 datetime 对象:

  • 时间戳转 datetime:
    datetime.datetime.fromtimestamp(time.time())
  • struct_time 转 datetime:
    先用 time.mktime(t) 转为时间戳,再用 fromtimestamp()
    例如:
    dt = datetime.datetime.fromtimestamp(time.mktime(struct_time_obj))

从datetime转换为time

如果已有 datetime 对象,想转为 struct_time 或时间戳:

  • datetime 转时间戳:
    timestamp = dt.timestamp()time.mktime(dt.timetuple())
  • datetime 转 struct_time:
    dt.timetuple() 直接返回对应的 struct_time

实际例子

快速对照:

import time
import datetime
<h1>当前时间</h1><p>now_struct = time.localtime()
now_dt = datetime.datetime.now()</p><h1>time → datetime</h1><p>dt_from_time = datetime.datetime.fromtimestamp(time.mktime(now_struct))</p><h1>datetime → time</h1><p>timestamp_from_dt = now_dt.timestamp()
struct_from_dt = now_dt.timetuple()</p>

基本上就这些,关键是理解时间戳是桥梁,struct_time 和 datetime 可通过它互转。

以上就是《time与datetime模块转换方法解析》的详细内容,更多关于的资料请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>