Skip to content Skip to sidebar Skip to footer

Human-readable Datetime Interval To Datetime.timedelta In Python?

I find myself needing to specify a timespan in a python configuration file a lot. Is there a way that I can specify a more human readable timeframe (similar to PostgreSQL's Inter

Solution 1:

I found a good answer to this in an somewhat related question. Turns out the humanfriendly library does that fairly well:

In[1]: importhumanfriendlyIn[2]: humanfriendly.parse_timespan('1w')
Out[2]: 604800.0

That's in seconds. To get a timedelta object, you can simply load that:

In [3]: from datetime import timedelta

In [4]: timedelta(seconds=humanfriendly.parse_timespan('1w'))
Out[4]: datetime.timedelta(7)

Since humanfriendly also supports converting the other way, you can also do full round trip, which would look like:

In [5]: humanfriendly.format_timespan(timedelta(seconds=humanfriendly.parse_timespan('1w')).total_seconds())
Out[5]: '1 week'

Note how format_timespan does not access timedelta objects, unfortunately: only an integer (seconds).

Solution 2:

I don't think there is a standard library module for that. I wrote one that does that. You can install it, or adapt it to your needs.

The module is called pycopia.timespec

It converts strings such as "1day 3min" to seconds, as a float. It's easy to get a datetime.timedelta from that.

Post a Comment for "Human-readable Datetime Interval To Datetime.timedelta In Python?"