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
• 5,870 points

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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 = - 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
• 9,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
• 56,100 points
0 votes
1 answer

How to convert to UTC timestamp in Python

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

answered Oct 31, 2018 in Python by Priyaj
• 56,100 points
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
+2 votes
2 answers

How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,710 points
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 920 points
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
• 9,300 points
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
• 9,300 points

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.