Python 如何从一个简单的字符串构造一个 timedelta 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4628122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to construct a timedelta object from a simple string
提问by priestc
I'm writing a function that needs a timedelta input to be passed in as a string. The user must enter something like "32m" or "2h32m", or even "4:13" or "5hr34m56s"... Is there a library or something that has this sort of thing already implemented?
我正在编写一个需要将 timedelta 输入作为字符串传入的函数。用户必须输入诸如“32m”或“2h32m”,甚至“4:13”或“5hr34m56s”之类的东西……是否有图书馆或已经实现了此类东西的东西?
采纳答案by virhilo
For the first format(5hr34m56s), you should parse using regular expressions
对于第一种格式(5hr34m56s),您应该使用正则表达式进行解析
Here is re-based solution:
这是重新基于的解决方案:
import re
from datetime import timedelta
regex = re.compile(r'((?P<hours>\d+?)hr)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?')
def parse_time(time_str):
parts = regex.match(time_str)
if not parts:
return
parts = parts.groupdict()
time_params = {}
for (name, param) in parts.iteritems():
if param:
time_params[name] = int(param)
return timedelta(**time_params)
>>> from parse_time import parse_time
>>> parse_time('12hr')
datetime.timedelta(0, 43200)
>>> parse_time('12hr5m10s')
datetime.timedelta(0, 43510)
>>> parse_time('12hr10s')
datetime.timedelta(0, 43210)
>>> parse_time('10s')
datetime.timedelta(0, 10)
>>>
回答by metakermit
To me the most elegant solution, without having to resort to external libraries such as dateutilor manually parsing the input, is to use datetime'spowerful strptimestring parsing method.
对我来说,最优雅的解决方案是使用datetime强大的字符串解析方法,而不必求助于诸如dateutil 之类的外部库或手动解析输入。strptime
from datetime import datetime, timedelta
# we specify the input and the format...
t = datetime.strptime("05:20:25","%H:%M:%S")
# ...and use datetime's hour, min and sec properties to build a timedelta
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
After this you can use your timedelta object as normally, convert it to seconds to make sure we did the correct thing etc.
在此之后,您可以照常使用 timedelta 对象,将其转换为秒以确保我们做了正确的事情等。
print(delta)
assert(5*60*60+20*60+25 == delta.total_seconds())
回答by wildwilhelm
I had a bit of time on my hands yesterday, so I developed @virhilo's answerinto a Python module, adding a few more time expression formats, including all those requested by @priestc.
昨天我有一些时间,所以我将@virhilo的答案开发到 Python 模块中,添加了更多时间表达式格式,包括@priestc请求的所有格式。
Source code is on github(MIT License) for anybody that wants it. It's also on PyPI:
源代码在 github(MIT 许可证)上,供任何需要的人使用。它也在 PyPI 上:
pip install pytimeparse
Returns the time as a number of seconds:
以秒数形式返回时间:
>>> from pytimeparse.timeparse import timeparse
>>> timeparse('32m')
1920
>>> timeparse('2h32m')
9120
>>> timeparse('4:13')
253
>>> timeparse('5hr34m56s')
20096
>>> timeparse('1.2 minutes')
72
回答by Alexey Kislitsin
If you use Python 3 then here's updated version for Hari Shankar's solution, which I used:
如果您使用 Python 3,那么这里是我使用的 Hari Shankar 解决方案的更新版本:
from datetime import timedelta
import re
regex = re.compile(r'(?P<hours>\d+?)/'
r'(?P<minutes>\d+?)/'
r'(?P<seconds>\d+?)$')
def parse_time(time_str):
parts = regex.match(time_str)
if not parts:
return
parts = parts.groupdict()
print(parts)
time_params = {}
for name, param in parts.items():
if param:
time_params[name] = int(param)
return timedelta(**time_params)
回答by kztd
I wanted to input just a time and then add it to various dates so this worked for me:
我只想输入一个时间,然后将其添加到不同的日期,所以这对我有用:
from datetime import datetime as dtt
time_only = dtt.strptime('15:30', "%H:%M") - dtt.strptime("00:00", "%H:%M")
回答by Peter
I've modified virhilo's nice answerwith a few upgrades:
我通过一些升级修改了virhilo 的好答案:
- added a assertion that the string is a valid time string
- replace the "hr" hour-indicator with "h"
- allow for a "d" - days indicator
- allow non-integer times (e.g.
3m0.25sis 3 minutes, 0.25 seconds)
- 添加了字符串是有效时间字符串的断言
- 用“h”替换“hr”小时指示器
- 允许使用 "d" - 天数指标
- 允许非整数时间(例如
3m0.25s3 分 0.25 秒)
.
.
import re
from datetime import timedelta
regex = re.compile(r'^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$')
def parse_time(time_str):
"""
Parse a time string e.g. (2h13m) into a timedelta object.
Modified from virhilo's answer at https://stackoverflow.com/a/4628148/851699
:param time_str: A string identifying a duration. (eg. 2h13m)
:return datetime.timedelta: A datetime.timedelta object
"""
parts = regex.match(time_str)
assert parts is not None, "Could not parse any time information from '{}'. Examples of valid strings: '8h', '2d8h5m20s', '2m4s'".format(time_str)
time_params = {name: float(param) for name, param in parts.groupdict().items() if param}
return timedelta(**time_params)
回答by Don Kirkby
Django comes with the utility function parse_duration(). From the documentation:
Django 自带实用功能parse_duration()。从文档:
Parses a string and returns a
datetime.timedelta.Expects data in the format
"DD HH:MM:SS.uuuuuu"or as specified by ISO 8601 (e.g.P4DT1H15M20Swhich is equivalent to4 1:15:20) or PostgreSQL's day-time interval format (e.g.3 days 04:05:06).
解析一个字符串并返回一个
datetime.timedelta.期望
"DD HH:MM:SS.uuuuuu"采用 ISO 8601(例如P4DT1H15M20S,等效于4 1:15:20)或 PostgreSQL 的日间时间间隔格式(例如3 days 04:05:06)指定的格式或指定的数据。
回答by jqmichael
Use isodatelibrary to parse ISO 8601 duration string. For example:
使用isodate库解析 ISO 8601 持续时间字符串。例如:
isodate.parse_duration('PT1H5M26S')
Also see Is there an easy way to convert ISO 8601 duration to timedelta?

