from datetime import timedelta
parse = lambda expr: timedelta(**dict((k, int(v)) for (k, v) in __import__('re').compile(' ?'.join(fr'((?P<{arg}>\d+){suffix})?' for (arg, suffix) in (('days', 'd'), ('hours', 'h'), ('minutes', 'm'), ('seconds', 's'), ('milliseconds', 'ms')))).match(expr).groupdict().items() if v))
>>> parse('1d 1h4m5s 14ms')
datetime.timedelta(days=1, seconds=3845, microseconds=14000)
如果真要用,务必先改改。
文章评论