diff --git a/faker/providers/date_time/__init__.py b/faker/providers/date_time/__init__.py index 0c67fb13fb..22aa0d4a50 100644 --- a/faker/providers/date_time/__init__.py +++ b/faker/providers/date_time/__init__.py @@ -1,3 +1,4 @@ +import functools import platform import re @@ -33,6 +34,19 @@ def timestamp_to_datetime(timestamp: Union[int, float], tzinfo: Optional[TzInfo] return convert_timestamp_to_datetime(timestamp, tzinfo) +def maybe_format_as_string(func): + """Format date as string if a pattern is provided.""" + @functools.wraps(func) + def wrapper(*args, **kwargs): + result: dtdate = func(*args, **kwargs) + pattern = kwargs.get('pattern') + if pattern: + return result.strftime(pattern) + return result + return wrapper + + + def change_year(current_date: dtdate, year_diff: int) -> dtdate: """ Unless the current_date is February 29th, it is fine to just subtract years. @@ -2167,18 +2181,21 @@ def date_time_between_dates( ) return pick + @maybe_format_as_string def date_between_dates( self, date_start: Optional[DateParseType] = None, date_end: Optional[DateParseType] = None, - ) -> dtdate: + pattern: Optional[str] = None, + ) -> Union[dtdate, str]: """ Takes two Date objects and returns a random date between the two given dates. Accepts Date or datetime objects :param date_start: Date :param date_end: Date - :return: Date + :param pattern: optional pattern to format the date as string + :return: Date or string """ return self.date_time_between_dates(date_start, date_end).date() diff --git a/tests/providers/test_date_time.py b/tests/providers/test_date_time.py index d708bf849e..f4956daf34 100644 --- a/tests/providers/test_date_time.py +++ b/tests/providers/test_date_time.py @@ -272,6 +272,15 @@ def test_date_between_dates(self): assert date_start <= random_date assert date_end >= random_date + def test_date_string_between_dates(self): + date_end = date.today() + date_start = date_end - timedelta(days=10) + date_format = "%Y-%m-%d" + + date_string = self.fake.date_between_dates(date_start, date_end, pattern=date_format) + assert isinstance(date_string, str) + assert isinstance(datetime.strptime(date_string, date_format), datetime) + def test_date_time_between_long_past_dates(self): random_date = self.fake.date_between("-100y", "-50y") assert random_date