本文介绍了来自:“1小时前”,至:timedelta +精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 例如,给定(字符串): '7小时前' '5天前' '2个月前' 可以返回(为伪代码道歉): datetime.now() - timedelta(1分钟),准确度(60秒) datetime.now ) - timedelta(7小时),准确度(1小时) datetime.now() - timedelta(5天),准确性(1天) datetime.now() - timedelta(2个月),准确度(1个月) 解决方案你不能只是自己写一个简单的实现,如: import datetime def parsedatetime (str_val): parts = str_val.split('') 如果len(parts)!= 3和parts [2]!='ago': raise异常(can not parse%s%str_val) try: interval = int(parts [0])除了ValueError,e: raise异常(无法解析%s%str_val) desc = parts [1] 如果desc中的'second': td = datetime.timedelta(seconds = interval) elif'min'in desc: td = datetime.timedelta(minutes = interval) elif'hour'in desc: td = datetime.timedelta(minutes = interval * 60) elif'day'in desc: td = datetime.timedelta(days = interval) else: raise异常(cant parse%s%str_val) answer = datetime。 datetime.now - td 返回答案 输入不显示 不同。 Is there a function to 'reverse humanize' times?For example, given (strings):'1 minute ago''7 hours ago''5 days ago''2 months ago'Could return (apologies for the pseudo-code):datetime.now() - timedelta (1 minute), accuracy (60 seconds)datetime.now() - timedelta (7 hours), accuracy (1 hour)datetime.now() - timedelta (5 days), accuracy (1 day)datetime.now() - timedelta (2 months), accuracy (1 month) 解决方案 Can you not just write a simple implementation yourself such as:import datetimedef parsedatetime(str_val): parts = str_val.split(' ') if len(parts) != 3 and parts[2] != 'ago': raise Exception("can't parse %s" % str_val) try: interval = int(parts[0]) except ValueError,e : raise Exception("can't parse %s" % str_val) desc = parts[1] if 'second' in desc: td = datetime.timedelta(seconds=interval) elif 'minute' in desc: td = datetime.timedelta(minutes=interval) elif 'hour' in desc: td = datetime.timedelta(minutes=interval*60) elif 'day' in desc: td = datetime.timedelta(days=interval) else: raise Exception("cant parse %s" % str_val) answer = datetime.datetime.now - td return answerThe input doesn't look that varied. 这篇关于来自:“1小时前”,至:timedelta +精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-29 03:24