Python获取类似“3小时前”格式时间的实际时间值
这个网上搜了一下,没有现成的pip模块可以用。
有一个timeago的模块,不过是反过来的,也就是给定具体时间,输出类似“3分钟前”,“3小时前”的时间格式,不符合要求。
我们要实现的是:输入3小时前,输出三小时前的实际时间,如:2019-07-0813:32:23
直接上代码吧,比较简单,用正则和哈希表来实现:
defget_real_time(delta_time):
"""
获取几秒钟前、几分钟前、几小时前、几天前,几个月前、及几年前的具体时间
:paramdelta_time格式如:50秒前,10小时前,31天前,5个月前,8年前
:return:具体时间%Y-%m-%d%H:%M:%S
"""
#获取表达式中的数字
delta_num=int(re.findall("\d+",delta_time)[0])
#获取表达式中的文字
delta_word=re.findall("\D+",delta_time)[0]
units={
"秒前":delta_num,
"秒钟前":delta_num,
"分钟前":delta_num*60,
"小时前":delta_num*60*60,
"天前":delta_num*24*60*60,
"个月前":int(delta_num*365.0/12)*24*60*60,
"月前":int(delta_num*365.0/12)*24*60*60,
"年前":delta_num*365*24*60*60,
}
delta_time=datetime.timedelta(seconds=units[delta_word])
return(datetime.datetime.now()-delta_time).strftime('%Y-%m-%d%H:%M:%S')
如果还有其他的时间差描述,扩展units哈希表即可。
如下是测试的结果:
现在2019-07-0817:39:41 3秒钟前2019-07-0817:39:38 3分钟前2019-07-0817:36:41 3小时前2019-07-0814:39:41 3天前2019-07-0517:39:41 3月前2019-04-0817:39:41 3年前2016-07-0817:39:41
如果要返回unix时间戳格式(int格式),返回语句改为:
returnint(time.mktime((datetime.datetime.now()-delta_time).timetuple()))
参考地址:
- python获取几小时之前,几分钟前,几天前,几个月前,及几年前的具体时间
- HowdoIcalculatethedatesixmonthsfromthecurrentdateusingthedatetimePythonmodule?