python 'x days ago' to datetime

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

x minutes/hours/days/months/years ago
 

Now if I need to parse that to a datetime using python, how should I do it?
Feb 26 in Python by ana1504.k
• 7,870 points
233 views

1 answer to this question.

0 votes
You just need a timedelta and try the following :

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
answered Feb 26 by SDeb
• 13,180 points

Related Questions In Python

0 votes
1 answer

How to use string.replace() in python 3.x

replace() is a method of <class 'str'> ...READ MORE

answered Aug 3, 2018 in Python by Priyaj
• 56,920 points
94 views
0 votes
1 answer

How to convert datetime.date to UTC timestamp in Python

In Python 3 (< 3.3) From the docs ...READ MORE

answered Oct 31, 2018 in Python by Priyaj
• 56,920 points
2,760 views
0 votes
1 answer

Python datetime: How to change month number to month name?

You can use the datetime module to ...READ MORE

answered May 9 in Python by Suman
1,184 views
0 votes
1 answer

How to convert Python Datetime to String without microsecond component?

If you want to format a datetime object in ...READ MORE

answered Aug 2 in Python by Shabnam
• 920 points
49 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 346 views
0 votes
1 answer

How to check the version of Python?

you can check the version of python ...READ MORE

answered Sep 25, 2018 in Python by SDeb
• 13,180 points
63 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 28, 2018 in Python by SDeb
• 13,180 points
81 views