Custom function to convert x hours ago to datetime , x hour, y mins ago to datetime , etc. In Python.
The function accepts a single parameter of type string, which is parsed using RegExp. RegExp can be customized according to the input function.
For use, see the examples below.
import re from datetime import datetime, timedelta def convert_datetime(datetime_ago): matches = re.search(r"(\d+ weeks?,? )?(\d+ days?,? )?(\d+ hours?,? )?(\d+ mins?,? )?(\d+ secs? )?ago", datetime_ago) if not matches: return None date_pieces = {'week': 0, 'day': 0, 'hour': 0, 'min': 0, 'sec': 0} for i in range(1, len(date_pieces) + 1): if matches.group(i): value_unit = matches.group(i).rstrip(', ') if len(value_unit.split()) == 2: value, unit = value_unit.split() date_pieces[unit.rstrip('s')] = int(value) d = datetime.today() - timedelta( weeks=date_pieces['week'], days=date_pieces['day'], hours=date_pieces['hour'], minutes=date_pieces['min'], seconds=date_pieces['sec'] ) return d
Usage example:
dates = [ '1 week, 6 days, 11 hours, 20 mins, 13 secs ago', '1 week, 10 hours ago', '1 week, 1 day ago', '6 days, 11 hours, 20 mins ago', '1 hour ago', '11 hours, 20 mins ago', '20 mins 10 secs ago', '10 secs ago', '1 sec ago', ] for date in dates: print(convert_datetime(date))
Exit:
2019-05-10 06:26:40.937027 2019-05-16 07:46:53.937027 2019-05-15 17:46:53.937027 2019-05-17 06:26:53.937027 2019-05-23 16:46:53.937027 2019-05-23 06:26:53.937027 2019-05-23 17:26:43.937027 2019-05-23 17:46:43.937027 2019-05-23 17:46:52.937027