Python字符串转时间戳

Python字符串转时间戳

Python字符串转时间戳

在Python中,时间戳是一个浮点数或整数,代表从1970年1月1日零点开始经过的秒数(Unix时间戳)。字符串是一种常见的时间表示形式,我们经常需要将字符串转换为时间戳来进行日期计算或比较。本文将详细介绍如何将字符串转换为时间戳。

1. 使用time模块

Python的time模块提供了很多处理时间的函数,包括将字符串转换为时间戳的功能。可以使用time.mktime()函数来实现这个功能。

import time

def str_to_timestamp(date_str):
    time_array = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    timestamp = time.mktime(time_array)
    return timestamp

date_str = "2022-01-01 12:00:00"
timestamp = str_to_timestamp(date_str)
print(timestamp)

上述代码中,time.strptime()函数将字符串按照指定的格式解析为时间元组,然后使用time.mktime()函数将时间元组转换为时间戳。最后打印出转换后的时间戳。

2. 使用datetime模块

除了time模块,Python还提供了datetime模块来处理时间。可以使用datetime模块的strptime()函数将字符串转换为datetime对象,再调用datetime对象的timestamp()方法获得时间戳。

from datetime import datetime

def str_to_timestamp(date_str):
    date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    timestamp = date_obj.timestamp()
    return timestamp

date_str = "2022-01-01 12:00:00"
timestamp = str_to_timestamp(date_str)
print(timestamp)

这段代码与上面的示例类似,只是使用了datetime.strptime()函数将字符串转换为datetime对象,然后调用timestamp()方法获取时间戳。

3. 示例

假设我们有一个字符串表示的时间”2022-01-01 12:00:00″,我们将使用上面的两种方法来将其转换为时间戳,并查看转换结果。

import time
from datetime import datetime

def str_to_timestamp_time(date_str):
    time_array = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    timestamp = time.mktime(time_array)
    return timestamp

def str_to_timestamp_datetime(date_str):
    date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    timestamp = date_obj.timestamp()
    return timestamp

date_str = "2022-01-01 12:00:00"
timestamp_time = str_to_timestamp_time(date_str)
timestamp_datetime = str_to_timestamp_datetime(date_str)

print("使用time模块转换的时间戳:", timestamp_time)
print("使用datetime模块转换的时间戳:", timestamp_datetime)

将上面的示例保存为一个Python脚本并运行,得到的输出将显示使用time模块和datetime模块转换的时间戳值:

使用time模块转换的时间戳: 1641028800.0
使用datetime模块转换的时间戳: 1641028800.0

可以看到,无论是使用time模块还是datetime模块,转换后的时间戳值都是一样的。

结论

本文介绍了在Python中将字符串转换为时间戳的两种方法:使用time模块和datetime模块。通过使用time.strptime()time.mktime()函数,或者使用datetime.strptime()timestamp()方法,我们可以方便地将字符串表示的时间转换为时间戳,以便进一步处理和计算。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程