Skip to content

Commit

Permalink
Add decorator to optionally format dates as string
Browse files Browse the repository at this point in the history
  • Loading branch information
browniebroke committed Sep 4, 2024
1 parent 01b90b5 commit 4d881ac
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
21 changes: 19 additions & 2 deletions faker/providers/date_time/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import functools
import platform
import re

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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()

Expand Down
9 changes: 9 additions & 0 deletions tests/providers/test_date_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4d881ac

Please sign in to comment.