Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 'x days ago' to datetime

I have strings that show a date in the following format:

x minutes/hours/days/months/years ago

I need to parse that to a datetime using python.

It seems dateutil can't do it.

Is there a way to do it?

like image 509
applechief Avatar asked Sep 24 '12 13:09

applechief


People also ask

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

What is datetime Timedelta in Python?

Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.

How do you get the next day in Python?

datetime() to format the given date . Then, Use givenDate + datetime. timedelta(days=1) to add one day from the given date and print result as next date in python.


1 Answers

Sure you can do it. You just need a timedelta.

s = "3 days ago"
parsed_s = [s.split()[:2]]
time_dict = dict((fmt,float(amount)) for amount,fmt in parsed_s)
dt = datetime.timedelta(**time_dict)
past_time = datetime.datetime.now() - dt

As an aside, it looks like dateutil has a relativedelta which acts like a timedelta, but the constructor also accepts months and years in the arguments (and apparently the arguments need to be integers).

like image 182
mgilson Avatar answered Oct 11 '22 04:10

mgilson