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?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With