一、使用场景
1、因为钉钉的api接口查询审批单据数据时审批时间需要安装时间戳查询数据。
2、其他时间转换成时间戳。
二、转换方法
1、使用time模块
1、安装模块
pip install time 安装时间模块
2、安装python-dateutil
pip3 install python-dateutil
3、转换代码如下
import datetime
from dateutil.relativedelta import relativedelta
import time
curr_time = datetime.datetime.now()
new_time_1 = str(curr_time.date())
new_time_2 = (curr_time + relativedelta(days=-3)).strftime("%Y-%m-%d %H:%M:%S") #天
new_time_3 = (curr_time + relativedelta(weeks=-1)).strftime("%Y-%m-%d %H:%M:%S") #周
new_time_4 = (curr_time + relativedelta(months=-1)).strftime("%Y-%m-%d %H:%M:%S") #月
print("前一天的时间是 %s" % new_time_2)
s_t = time.strptime(new_time_2, "%Y-%m-%d %H:%M:%S") #将获取的时间序列化
mkt = int(round(time.mktime(s_t)))#转换成毫米级时间戳
print("当前的时间戳 %s" % curr_time)
'''
print("当前的日期和时间是 %s" % curr_time)
print("当前的年份是 %s" % curr_time.year)new_time_2
print("当前的月份是 %s" % curr_time.month)
print("当前的日期是 %s" % curr_time.day)
print("当前小时是 %s" % curr_time.hour)
print("当前分钟是 %s" % curr_time.minute)
print("当前秒是 %s" % curr_time.second)
print("当前的日期是 %s" % new_time_1)
print("前一天的时间是 %s" % new_time_2)
print("前一周的时间是 %s" % new_time_3)
print("前一月的时间是 %s" % new_time_4)
'''
print(mkt)
打印效果
前一天的时间是 2022-10-03 15:50:22
当前的时间戳 1664783422
代码参考与网络