There are some libraries to help converting time delta into human-readable formats, for examples:
1 day, 4 hours, 5 seconds
1.5h
Some outputs like those. But how to reverse in your want to get the seconds of the durations? simpleduration (GitHub) is what you are looking for, from its README:
>>> from simpleduration import Duration
>>> d = Duration("10 minutes")
>>> d.timedelta().total_seconds()
600.
>>> d = Duration("1 day, 4 hours, 5 seconds")
>>> d.timedelta().total_seconds()
100805.0
>>> Duration("1.5h").timedelta().total_seconds()
5400.0
>>> d1 = Duration("10 minutes")
>>> d2 = Duration("20 minutes")
>>> d3 = Duration("30 minutes")
>>> (d1 + d2) == d3
True
>>> d1 += d3
>>> d1.timedelta().total_seconds()
2400.0
You use Duration class initialization to parse the time duration string, it provides a timedelta() method, so you can get a datetime.timedelta object for total_seconds().
The parsing is very flexible, it understands some common abbreviations of time units, such as “m’, “hr”, etc. Case insensitive, white spaces and punctuations are ignored. It can even parse same unit more than once:
>>> Duration('10m 10m').timedelta()
datetime.timedelta(0, 1200)
It’s just like sleep, my favorite command, very flexible in parsing.
I took a look at its source, honestly, I don’t think it’s a good implementation, whether it’s using regular expression to parse or not isn’t really that important, which it isn’t. I wanted to add a couple of ignored words for “and” and “ago” since they could appear in the human-readable format. However, I don’t think there is a very simple way to edit the code without understand most of its code first.
simpleduration is written by Anders Pearson for both Python 2 and 3 under BSD License, currently version 0.1.0 (2014-04-13).
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.