From 9e62f283ffd07ddb19de8b9f03db377aad369cc1 Mon Sep 17 00:00:00 2001 From: colethedj Date: Tue, 6 Apr 2021 18:45:15 +1200 Subject: [utils] Add `datetime_from_str` to parse relative time (#221) and `datetime_add_months` to accurately add/subtract months Authored by: colethedj --- yt_dlp/utils.py | 86 +++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 18 deletions(-) (limited to 'yt_dlp/utils.py') diff --git a/yt_dlp/utils.py b/yt_dlp/utils.py index c14fdb509..3ba2a1ec8 100644 --- a/yt_dlp/utils.py +++ b/yt_dlp/utils.py @@ -3052,33 +3052,83 @@ def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None): return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext) -def date_from_str(date_str): +def datetime_from_str(date_str, precision='auto', format='%Y%m%d'): """ Return a datetime object from a string in the format YYYYMMDD or - (now|today)[+-][0-9](day|week|month|year)(s)?""" - today = datetime.date.today() + (now|today|date)[+-][0-9](microsecond|second|minute|hour|day|week|month|year)(s)? + + format: string date format used to return datetime object from + precision: round the time portion of a datetime object. + auto|microsecond|second|minute|hour|day. + auto: round to the unit provided in date_str (if applicable). + """ + auto_precision = False + if precision == 'auto': + auto_precision = True + precision = 'microsecond' + today = datetime_round(datetime.datetime.now(), precision) if date_str in ('now', 'today'): return today if date_str == 'yesterday': return today - datetime.timedelta(days=1) - match = re.match(r'(now|today)(?P[+-])(?P