一、背景
举例:理论上2.31与1.31相隔一个月,但是2月并没有31天。实际爬虫过程中我们又必须将满足“2.31”这一天的数据推到MQ爬取,那么该怎么控制最好呢?
二、思路
如上述,2月没有31号,那么我们在二月份的极限能取到几号?我们只能取到2.28或2.29。那我们是不是能理解成一个特定的时间点(如:1.31),它在下个月对应的时间与其差距最多为2月最大天数(28或29)。
综上我们可以总结为:某个时间戳(x)在下个月对应的时间戳(y)为该时间戳(x)+下个月最大天数(z),y=x+z
三、代码
import time
import datetime
def get_date_p(time_stamp):
"""
获取格式为2020-02-28,类型为datetime.datetime的数据
:param time_stamp: 时间戳
:return:
"""
time_array = time.localtime(time_stamp)
other_style_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
date_time_p = datetime.datetime.strptime(other_style_time, '%Y-%m-%d %H:%M:%S')
date_p = date_time_p.date()
return date_p
def get_month_days(time_stamp):
"""
获取该月有几天
:param time_stamp: 时间戳
:return:
"""
current_time = get_date_p(time_stamp)
current_month_first_day = datetime.datetime(current_time.year, current_time.month, 1)
current_month_last_day = datetime.datetime(current_time.year, current_time.month + 1, 1)
current_month_days = (current_month_last_day - current_month_first_day).days
return current_month_days
def one_month_currently(last_time, current_time):
"""
计算两个时间戳是够相隔一个月
:param last_time: 上一个月的时间戳
:param current_time: 当前时间戳
:return: True:相差一个月,False:无
"""
month_days = get_month_days(current_time)
last_time_date = get_date_p(last_time)
current_time_data = get_date_p(current_time)
days = (current_time_data - last_time_date).days
if days >= month_days:
print("ok")
return True
else:
print("no")
return False
one_month_currently(1577845071, 1582856271)