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, 2019 in Python by ana1504.k
• 7,910 points
2,954 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, 2019 by SDeb
• 13,300 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
• 58,020 points
1,169 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
• 58,020 points
9,959 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, 2019 in Python by Suman
13,495 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, 2019 in Python by Shabnam
• 930 points
2,189 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,467 views
0 votes
1 answer
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,300 points
810 views
0 votes
1 answer

How to Reverse a list in Python

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

answered Sep 29, 2018 in Python by SDeb
• 13,300 points
864 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP