Coder Social home page Coder Social logo

pytimeparse's Introduction

pytimeparse: time expression parser

Travis CI build status

Test code coverage

Latest Version

Copyright (c) 2014 Will Roberts <[email protected]>

Licensed under the MIT License (see source file timeparse.py for details).

A small Python library to parse various kinds of time expressions, inspired by this StackOverflow question.

The single function pytimeparse.timeparse.timeparse defined in the library (also available as pytimeparse.parse) parses time expressions like the following:

  • 32m
  • 2h32m
  • 3d2h32m
  • 1w3d2h32m
  • 1w 3d 2h 32m
  • 1 w 3 d 2 h 32 m
  • 4:13
  • 4:13:02
  • 4:13:02.266
  • 2:04:13:02.266
  • 2 days, 4:13:02 (uptime format)
  • 2 days, 4:13:02.266
  • 5hr34m56s
  • 5 hours, 34 minutes, 56 seconds
  • 5 hrs, 34 mins, 56 secs
  • 2 days, 5 hours, 34 minutes, 56 seconds
  • 1.2 m
  • 1.2 min
  • 1.2 mins
  • 1.2 minute
  • 1.2 minutes
  • 172 hours
  • 172 hr
  • 172 h
  • 172 hrs
  • 172 hour
  • 1.24 days
  • 5 d
  • 5 day
  • 5 days
  • 5.6 wk
  • 5.6 week
  • 5.6 weeks

It returns the time as a number of seconds (an integer value if possible, otherwise a floating-point number):

>>> from pytimeparse import parse
>>> parse('1.2 minutes')
72

A number of seconds can be converted back into a string using the datetime module in the standard library, as noted in this other StackOverflow question:

>>> from pytimeparse import parse
>>> import datetime
>>> parse('1 day, 14:20:16')
138016
>>> str(datetime.timedelta(seconds=138016))
'1 day, 14:20:16'

Future work

  1. Give the user more flexibility over which characters to use as separators between fields in a time expression (e.g., + might be useful).
  2. Internationalisation?
  3. Wow, https://github.com/bear/parsedatetime .

pytimeparse's People

Contributors

cackovic avatar catherinedevlin avatar duramato avatar jd avatar sileht avatar wroberts avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytimeparse's Issues

Feature Request: Days-HH:MM:SS support

I'm currently working on some metric work coming out of the job scheduler 'slurm', it records elapsed time as:

1-04:18:35  ## multi day elapsed time
12:25:02 ## single day time

I'd be great to be able to handle this directly instead of having a pre-check.

Months support doesn't seem to work

Hello! Based on #7 and the PR #10 from @duramato, I expected to be able to use an expression like "1 month" using the current HEAD, but that doesn't seem to actually work:

$  mkvirtualenv foo
$ workon foo
$ pip install -e -e git://github.com/wroberts
$ pip install -e git://github.com/wroberts/pytimeparse.git@cc0550d3f4ec72d745ef2387603005ab52aa9538#egg=pytimeparse
Obtaining pytimeparse from git+git://github.com/wroberts/pytimeparse.git@cc0550d3f4ec72d745ef2387603005ab52aa9538#egg=pytimeparse
  Cloning git://github.com/wroberts/pytimeparse.git (to cc0550d3f4ec72d745ef2387603005ab52aa9538) to ./.virtualenvs/foo/src/pytimeparse
  Could not find a tag or branch 'cc0550d3f4ec72d745ef2387603005ab52aa9538', assuming commit.
Installing collected packages: pytimeparse
  Running setup.py develop for pytimeparse
Successfully installed pytimeparse
(foo) โžœ  ~  python
Python 2.7.12 (default, Jun 29 2016, 14:05:02)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pytimeparse.timeparse import timeparse
>>> timeparse("1 month")
>>> timeparse("30 days")
2592000
>>>

ValueError is raised instead of returning None for 'parse(". day")'

Hello.

I just noticed a small bug. This is not very important, but it's a little inconsistent with the rest of the library which returns None when unable to parse the string.

>>> from pytimeparse import parse
>>> parse(". day")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/env/lib/python3.6/site-packages/pytimeparse/timeparse.py", line 176, in timeparse
    list(mdict.items()) if k != 'secs' and v is not None])) +
  File "/home/env/lib/python3.6/site-packages/pytimeparse/timeparse.py", line 176, in <listcomp>
    list(mdict.items()) if k != 'secs' and v is not None])) +
ValueError: could not convert string to float: '.'

Python 3.6.3 and pytimeparse 1.1.7.

I guess this is because of the regex [\d.]+ which do not filter out such wrongly formatted float values.

New release?

Hi there! Since #10, there hasn't been a release. I'd love to use this new functionality. Can you release to PyPI?

pip install from PyPI failing

Installing works fine from the github repo, but I'm getting a failure with pip.

(ipy1) {master} ~/sw/pytimeparse$ python --version
Python 2.7.4
(ipy1) {master} ~/sw/pytimeparse$ pip install pytimeparse
Downloading/unpacking pytimeparse
  Downloading pytimeparse-1.0.0.tar.gz
  Running setup.py egg_info for package pytimeparse
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/home/catherine/ve/ipy1/build/pytimeparse/setup.py", line 13, in <module>
    with open('README.rst') as file:
    IOError: [Errno 2] No such file or directory: 'README.rst'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/home/catherine/ve/ipy1/build/pytimeparse/setup.py", line 13, in <module>

    with open('README.rst') as file:

IOError: [Errno 2] No such file or directory: 'README.rst'

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /home/catherine/ve/ipy1/build/pytimeparse
Storing complete log in /tmp/tmpQf_lo8

I might be able to look for a fix in a couple days.

Support for negative timedeltas

Hi! Thank you for your library, I just wanna know is it likely that you will add support for negative deltas? For example

timeparse('-1 days -00:00:14.513431')

gives None, why it would be nice (at least for my purpose) to get negative number of seconds in this delta. Probably also output should be the same for such input

timeparse('-1 days 00:00:14.513431')

It's not crucial and could be circumvented of course, but would be nice to have it from the box, thank you)

Question

Thank you for this, for the past year I have used this in all projects needing it, on a daily basis.
Is there any way I can donate?

Subsecond precision

Cool project. I would have found it a good fit for my work but I also needed sub-second precision.

>>> import pytimeparse
>>> pytimeparse.parse('1ms')
>>> 

I thought I'd raise an issue here as a feature request.

License file

I am trying to package pytimeparse for openSUSE. However, there is no license file I can find, either in the github or tarball. In order for people to know how they can use your code it is really important to have a license file. Would it be possible to add one? Thank you.

Feature Request: Milliseconds Support

Hi there
It would be nice to add milliseconds support to this tool

I was able to do that at runtime by overriding some internal values with the following code part:

import re
from pytimeparse import timeparse
timeparse.MILLIS = r'(?P<millis>[\d.]+)\s*(?:ms|msecs?|millis|milliseconds?)'
timeparse.TIMEFORMATS[0] += r'\s*' + timeparse.OPT(timeparse.MILLIS)
timeparse.MULTIPLIERS['millis'] = 1e-3
timeparse.COMPILED_TIMEFORMATS[0] = re.compile(r'\s*' + timeparse.TIMEFORMATS[0] + r'\s*$', re.I)

No module named future.builtins

Hey, nice Module so far. But if i want to use it in a python program i get the following error:

Traceback (most recent call last):
    File "./rollup.py", line 13, in <module>
    from repositories.rollout  import RolloutRepository
  File "/vagrant/app/repositories/rollout.py", line 8, in <module>
    from models.rollout import Rollout
  File "/vagrant/app/models/rollout.py", line 5, in <module>
    from pytimeparse.timeparse import timeparse
  File "/usr/local/lib/python2.6/dist-packages/pytimeparse/timeparse.py", line 1, in <module>
    from future.builtins import dict
ImportError: No module named future.builtins

I have the following version of python (its an old server :)

$ python --version
Python 2.6.6

thx in advance and cheers
Sascha

add argparse utility for parsing to timedelta

i dont know if you think its good to put in the lib but i have something like:

class TimeDeltaAction(argparse.Action):

    def parse(self, value):
        parsed = pytimeparse.parse(value)
        if parsed is None:
            raise argparse.ArgumentError(
                self, '"{0}" invalid time-delta expression'.format(value),
            )
        return timedelta(seconds=parsed)

    # argparse.Action

    def __call__(self, parser, namespace, values, option_string=None):
        if isinstance(values, basestring):
            setattr(namespace, self.dest, self.parse(values))
        else:
            setattr(namespace, self.dest, map(self.parse, values))

copied around. would you consider a patch that adds it to pytimeparse?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.