Python获取类似“3小时前”格式时间的实际时间值

2.6k 记录 发表评论

这个网上搜了一下,没有现成的pip模块可以用。

有一个timeago的模块,不过是反过来的,也就是给定具体时间,输出类似“3分钟前”,“3小时前”的时间格式,不符合要求。

我们要实现的是:输入3小时前,输出三小时前的实际时间,如:2019-07-08 13:32:23

直接上代码吧,比较简单,用正则和哈希表来实现:

def get_real_time(delta_time):
"""
获取几秒钟前、几分钟前、几小时前、几天前,几个月前、及几年前的具体时间
:param delta_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-08 17:39:41
 3秒钟前     2019-07-08 17:39:38
 3分钟前     2019-07-08 17:36:41
 3小时前     2019-07-08 14:39:41
 3天前      2019-07-05 17:39:41
 3月前      2019-04-08 17:39:41
 3年前      2016-07-08 17:39:41

如果要返回unix时间戳格式(int格式),返回语句改为:

return int(time.mktime((datetime.datetime.now() - delta_time).timetuple())) 

参考地址:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

昵称 *