深度阅读

How to Convert DateTime to UNIX timestamp in Python

作者
作者
2023年08月22日
更新时间
14.06 分钟
阅读时间
0
阅读量

To convert a datetime object to a UNIX timestamp in Python, you can use the time.mktime() function from the built-in time module. This function takes a struct_time object (which can be obtained from a datetime object using the timetuple() method) as input and returns the corresponding UNIX timestamp in seconds.

Here’s an example:

import datetime
import time

my_datetime = datetime.datetime(2022, 2, 19, 12, 0, 0)
unix_timestamp = int(time.mktime(my_datetime.timetuple()))

print(unix_timestamp)   # Output: 1645288800

In this example, we define a datetime object my_datetime containing the value of February 19, 2022 at 12:00:00. We use the timetuple() method to convert the datetime object to a struct_time object, which is then passed to the time.mktime() function to convert it to a UNIX timestamp in seconds. The resulting value in unix_timestamp is equivalent to the number of seconds that have elapsed since the UNIX epoch (January 1, 1970 at 00:00:00 UTC) to the input datetime object.

Note that the UNIX timestamp is typically represented as an integer, so we use the int() function to convert the output of time.mktime() to an integer.

In general, converting a datetime object to a UNIX timestamp can be useful when you need to perform datetime arithmetic or when passing datetime values as arguments to functions that expect UNIX timestamps.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。