JohnnyLoo
JohnnyLoo

Reputation: 927

Python - Convert human time quantity to seconds

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

Upvotes: 2

Views: 126

Answers (1)

CryptoFool
CryptoFool

Reputation: 23079

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.

Upvotes: 2

Related Questions