简体   繁体   中英

Human readable delta time text to Python `timedelta`

I have seen many examples on how to parse a human readable text containing a date/time to datetime structure or even seconds since "Epoch".

A few Pyhton libraries (eg parsedatetime or dateparser claim to be able to parse relative date/times (like "1min 47 seconds ago") but the end result is always anchored to a specific date/time.

Example using two mentioned libraries:

sdate="1 min 37 seconds ago"
dateparser.parse(sdate)
datetime.datetime(2019, 8, 19, 17, 20, 29, 325230)
pdtCal.parse(sdate)
(time.struct_time(tm_year=2019, tm_mon=8, tm_mday=19, tm_hour=17, tm_min=22, tm_sec=49, tm_wday=0, tm_yday=231, tm_isdst=-1), 2)

What I need, though, is something as simple as a timedelta object, but from what I could learn, the best I can do is to compute the timedelta by subtracting the parsed datetime from current time.

Obviously, this is not the same since I will be adding a sampling error ( datetime.datetime.now() is running at a different time as the parser run).

So I ask, is there a simple yet relieble way in Python to parse this delta time text directly into a timedelta object or a scalar value (eg seconds count)?

Thanks!

There is a way to specify "anchor date" in dateparser using settings :

In [1]: from dateparser import parse
In [2]: from datetime import datetime

In [3]: anchor_date = datetime(2020, 1, 1)
In [4]: parsed_date = parse('1 min 37 seconds ago', settings={'RELATIVE_BASE': anchor_date})
In [5]: parsed_date - anchor_date
Out[5]: datetime.timedelta(days=-1, seconds=86303)

Using the same date as relative base and in delta calculation ensures precise results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM