首先要获取分钟,小时,天,月,年的整数值,这个就是字符串的处理
import datetime
import arrow
def getTime(flag, dayhourminute):
'''
获取几小时之前,几分钟前,几秒前,几天前,几个月前,及几年前的具体时间
:param flag: 1:天;2:小时;3:分钟;4:秒,5:月,6:年,
:param dayhourminute: 整数值
:return: 具体时间 %Y-%m-%d %H:%M:%S
'''
tn = datetime.datetime.now()
t = None
ttime = ''
if flag <= 4:
if flag == 1: # 天
t = datetime.timedelta(days=dayhourminute)
elif flag == 2: # 小时
t = datetime.timedelta(hours=dayhourminute)
elif flag == 3: # 分钟
t = datetime.timedelta(minutes=dayhourminute)
elif flag == 4: # 秒
t = datetime.timedelta(seconds=dayhourminute)
datetime.timedelta()
strtime = tn - t
ttime = strtime.strftime('%Y-%m-%d %H:%M:%S')
else: # 处理月和年
dt = arrow.now()
if flag == 5:
ttime = dt.shift(months=-dayhourminute).format("YYYY-MM-DD HH:MM:SS") # 处理月份
elif flag == 6: # 处理年份
ttime = str(
int(datetime.datetime.now().strftime("%Y")) - dayhourminute) + "-" + datetime.datetime.now().strftime(
"%m-%d %H:%M:%S")
return ttime
网友评论