如何将 Python 日期转换为 Unix 时间戳?
UNIX 时间戳是从纪元开始计算的总秒数。纪元是时间的起点,并且取决于平台。在 Windows 和大多数 Unix 系统上,纪元是 1970 年 1 月 1 日 00:00:00(UTC),并且自纪元以来的时间(以秒为单位)中不包括闰秒。
在本文中,我们将了解如何将 Python 日期转换为 UNIX 时间戳。
日期时间转换为 UNIX 时间戳
在这里,我们使用 time.mktime() 方法 将 Python 日期转换为 UNIX 时间戳。在此示例中,我们最初导入了 datetime 模块。然后我们声明并分配了一个 datetime.time/date(2022, 6, 3, 12, 0, 50)。time.mktime() 是本地时间的反函数。time.mktime() 方法接受 time.struct_time 对象或包含 9 个元素的元组,并返回一个浮点值,该值表示自纪元以来的时间(以秒为单位)。
语法
mktime() 方法的语法如下所示。
time.mktime(t)
其中,t 是 time.struct_time 对象或包含 9 个元素的元组,这些元素对应于 time.struct_time 对象。
datetime.date 实例的 timetuple() 方法返回一个 time.struct_time 类型的对象。此对象使用 time.mktime() 方法转换为 UNIX 时间戳。
示例
以下是一个将 Python 日期转换为 UNIX 时间戳的示例代码。
import datetime import time date_time = datetime.datetime(2022, 6, 3, 12, 0, 50) print("Given Date:",date_time) print("UNIX timestamp:", (time.mktime(date_time.timetuple())))
输出
以上代码的输出如下所示:
Given Date: 2022-06-03 12:00:50 UNIX timestamp: 1654257650.0
日期时间到 UTC 时区的 UNIX 时间戳。
在这里,我们可以使用 datetime 模块将日期时间转换为 Python 中的 UTC 时间戳。如果您已经拥有 UTC 中的日期时间对象,则可以使用 timestamp() 获取 UTC 时间戳。此函数返回该日期时间对象自纪元以来的时间。如果您在本地时区中拥有日期时间对象,请先替换时区信息,然后再获取时间。
示例
以下是一个将日期时间转换为 UNIX 时间戳的示例代码。
import datetime from datetime import timezone dt = datetime.datetime(2022, 6, 7) timestamp = dt.replace(tzinfo=timezone.utc).timestamp() print("The timestamp for the date 06-07-2022 is:",timestamp)
输出
The timestamp for the date 06-07-2022 is: 1654560000.0
日期时间字符串转换为 UNIX 时间戳
在这种情况下,我们将以字符串格式表示的日期时间转换为 UNIX 时间戳。
示例
import datetime given_date = "8/6/2022, 05:54:8" formated_date = datetime.datetime.strptime(given_date,"%m/%d/%Y, %H:%M:%S") Unix_timestamp = datetime.datetime.timestamp(formated_date) print("The Unix timestamp for the given input date is:") print(Unix_timestamp)
输出
The Unix timestamp for the given input date is: 1659765248.0
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP