开发者

Convert relative date string to absolute date

As input, I have a date string that can take three general formats:

a) January 6, 2011 b) 4 days ago c) 12 hours ago

I want the script to be able to recognize the format and call the appropriate function with the parameters.

So if a then convert_full_string("January 6, 2011")

if b then convert_days(4)

if c then convert_hours(12)

Once I recognize the format and able to call the appropriate function, it will be relatively easy. I plan on using dateutil

But I am not sure how to recognize the format.

Any suggestions with code samples much apprec开发者_运维技巧iated.


Using parsedatetime, you could parse all three date formats into datetime.datetime objects without having to code the logic yourself:

import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import datetime
c = pdc.Constants()
p = pdt.Calendar(c)
for text in ('january 6, 2011', '4 days ago', '12 hours ago'):
    date=datetime.datetime(*p.parse(text)[0][:6])
    # print(date.isoformat())
    # 2011-01-06T09:00:18
    # 2011-01-02T09:00:18
    # 2011-01-05T21:00:18
    print(date.strftime('%Y%m%dT%H%M%S'))
    # 20110106T090208
    # 20110102T090208
    # 20110105T210208


if 'days' in userinput: 
    convert_days(userinput[:userinput.index('days')].strip())
elif 'hours' in userinput:
    convert_hours(userinput[:userinput.index('hours')].strip())
else:
    convert_full_string(userinput)

This assumes that when "days" or "hours" is contained in userinput, you always want the chars that came immediately before those two words.


You can match with regular expressions:

import re
re.search(r".* [0-9]{1,2}, [0-9]{4}", tomatch)

Similar with [0-9]{1,2} days ago, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜