Python 时间戳( timestamp)

您所在的位置:网站首页 java添加数据到数据库获取时间戳 Python 时间戳( timestamp)

Python 时间戳( timestamp)

2024-07-06 04:50| 来源: 网络整理| 查看: 265

Python time 模块Python 获取当前时间 Python 时间戳( timestamp)

在本文中,您将学习如何将时间戳转换为datetime对象,将datetime对象转换为时间戳(通过示例)。

将日期和时间作为时间戳存储在数据库中是很常见的。Unix时间戳是UTC特定日期到1970年1月1日之间的秒数。

示例1:Python时间戳到日期时间from datetime import datetime timestamp = 1545730073 dt_object = datetime.fromtimestamp(timestamp) print("dt_object =", dt_object) print("type(dt_object) =", type(dt_object))

运行该程序时,输出为:

dt_object = 2018-12-25 09:27:53 type(dt_object) = 

在这里,我们从datetime模块导入了datetime类。然后,我们使用了datetime.fromtimestamp()类方法,该方法返回本地日期和时间(datetime对象)。该对象存储在dt_object变量中。

注意:您可以使用strftime()方法轻松地从datetime对象创建表示日期和时间的字符串。

示例2:Python日期时间到时间戳

您可以使用datetime.timestamp()方法从datetime对象获取时间戳。

from datetime import datetime # 当前日期和时间 now = datetime.now() timestamp = datetime.timestamp(now) print("时间戳 =", timestamp)

                                                                                                                                                                                                   

Python time 模块Python 获取当前时间


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3