Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

How can I parse free-text time intervals in Python, ranging from years to seconds?

I would like to parse free-text time intervals like the following, using Python:

  • 1 second
  • 2 minutes
  • 3 hours
  • 4 days
  • 5 weeks
  • 6 months
  • 7 years

Is there a painless way to do this, ideally by simply calling a library function?

I have tried:

  • dateutil.parser.parse(), which understands seconds through hours but not days or more.
  • mx.DateTime.DateTimeDeltaFrom(), which understands through days but fails on weeks or higher, and silently (e.g., it might create an interval of length 0, or parse "2 months" as 2 minutes).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This one is new to me, but based on some googling have you tried whoosh?

Edit: There's also parsedatetime:

#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime

cal = pdt.Calendar()
for time_str in ['1 second', '2 minutes','3 hours','5 weeks','6 months','7 years']:
    diff = cal.parseDT(time_str, sourceTime=datetime.min)[0] - datetime.min
    print("{time_str:<10} -> {diff!s:>20} <{diff!r}>".format(**vars()))

Output

1 second   ->              0:00:01 <datetime.timedelta(0, 1)>
2 minutes  ->              0:02:00 <datetime.timedelta(0, 120)>
3 hours    ->              3:00:00 <datetime.timedelta(0, 10800)>
5 weeks    ->     35 days, 0:00:00 <datetime.timedelta(35)>
6 months   ->    181 days, 0:00:00 <datetime.timedelta(181)>
7 years    ->   2556 days, 0:00:00 <datetime.timedelta(2556)>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...