2

In Perl, there is a module, named 'Time::Duration::Parse', that lets you give it a time quantity using natural human language and converts that to seconds. Here is an example of what it does

use Time::Duration::Parse;

say parse_duration( "1 day and 2 seconds"); # I get 86402
say parse_duration( "7 seconds");           # I get 7
say parse_duration( "5m");                  # I get 300
say parse_duration( "1 year and 5 months"); # I get 44496000

Is there anything similar in for Python? I really hope because this library is very useful.

Thank you

toolic
  • 57,801
  • 17
  • 75
  • 117
JohnnyLoo
  • 877
  • 1
  • 11
  • 22
  • Does this answer your question? [How can I parse free-text time intervals in Python, ranging from years to seconds?](https://stackoverflow.com/questions/9775743/how-can-i-parse-free-text-time-intervals-in-python-ranging-from-years-to-second) – ksbg Sep 27 '22 at 04:27

1 Answers1

2

The dateparser package will do this for you. It's a bit involved to get it to simple seconds, but it works great in the end:

import dateparser
import datetime
    
def test(str):
    relative_base = datetime.datetime(2020, 1, 1)
    d = int((relative_base - dateparser.parse(str, settings={'RELATIVE_BASE': relative_base})).total_seconds())
    print(f"{str} -> {d}")

test("1 day and 2 seconds")
test("7 seconds")
test("5m")
test("1 year and 5 months")

Result:

1 day and 2 seconds -> 86402
7 seconds -> 7
5m -> 300
1 year and 5 months -> 44755200

I expect that the difference between the results for the last case is due to the packages making different assumptions about the number of days in a month, which is admittedly ambiguous.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44