Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 appreciated.

like image 456
Ted Karmel Avatar asked Oct 18 '25 05:10

Ted Karmel


1 Answers

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
like image 159
unutbu Avatar answered Oct 20 '25 18:10

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!