如何编写Python函数将日期转换为UNIX时间戳
发布时间:2023-06-23 00:50:40
UNIX时间戳是1970年1月1日至今的秒数,是一种通用的时间表示方式。Python中有多种处理日期和时间的库,在本文中将介绍如何使用Python内置的datetime库来编写函数将日期转换为UNIX时间戳。
步,导入datetime库:
import datetime
第二步,定义函数:
def date_to_timestamp(date):
# 将输入的日期字符串解析为datetime对象
datetime_obj = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
# 计算从1970年1月1日零时零分零秒到datetime对象的秒数
timestamp = (datetime_obj - datetime.datetime(1970, 1, 1)).total_seconds()
# 返回UNIX时间戳
return int(timestamp)
在上面的代码中,我们定义了一个名为date_to_timestamp的函数,它接受一个日期字符串作为输入,返回一个整型的UNIX时间戳。
函数的 步是将输入的日期字符串解析为datetime对象,这里使用了strptime函数,它可以将字符串按照指定格式解析为datetime对象。在本例中,日期字符串的格式为'%Y-%m-%d %H:%M:%S',表示年-月-日 小时:分钟:秒。
第二步是计算从1970年1月1日零时零分零秒到datetime对象的秒数,这里使用了total_seconds函数。datetime.datetime(1970, 1, 1)表示1970年1月1日零时零分零秒的datetime对象,datetime_obj - datetime.datetime(1970, 1, 1)表示datetime_obj与1970年1月1日零时零分零秒相差的时间,total_seconds()函数用来计算相差的秒数。
最后一步是将计算出的秒数转换为整型的UNIX时间戳,这里使用了int()函数。
下面是一个完整的例子,演示如何使用date_to_timestamp函数将日期转换为UNIX时间戳:
import datetime
def date_to_timestamp(date):
datetime_obj = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
timestamp = (datetime_obj - datetime.datetime(1970, 1, 1)).total_seconds()
return int(timestamp)
date_str = '2022-01-01 00:00:00'
timestamp = date_to_timestamp(date_str)
print(timestamp)
输出结果为:
1640995200
这个数值表示从1970年1月1日零时零分零秒到2022年1月1日零时零分零秒的秒数。
