Date Hashing and Generation Function
Below is a Python function that hashes a date and generates a new valid date within a given range.
import hashlib
import datetime
import random
def hash_date(date_str):
"""
Hashes a date string using SHA-256.
Args:
date_str (str): Date string in YYYY-MM-DD format.
Returns:
str: Hashed date string.
"""
return hashlib.sha256(date_str.encode()).hexdigest()
def generate_random_date(begin_date, end_date):
"""
Generates a random date within a given range.
Args:
begin_date (str): Start date in YYYY-MM-DD format.
end_date (str): End date in YYYY-MM-DD format.
Returns:
str: Random date string in YYYY-MM-DD format.
"""
begin_date_obj = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
end_date_obj = datetime.datetime.strptime(end_date, "%Y-%m-%d")
random_date_obj = begin_date_obj + datetime.timedelta(
seconds=random.randint(0, int((end_date_obj - begin_date_obj).total_seconds())),
)
return random_date_obj.strftime("%Y-%m-%d")
def main():
# Example usage
date_str = "2022-01-01"
hashed_date = hash_date(date_str)
print(f"Hashed date: {hashed_date}")
begin_date = "2020-01-01"
end_date = "2022-12-31"
random_date = generate_random_date(begin_date, end_date)
print(f"Random date: {random_date}")
if __name__ == "__main__":
main()
Explanation
- The
hash_date function takes a date string in YYYY-MM-DD format, encodes it, and hashes it using SHA-256.
- The
generate_random_date function takes a begin date and end date in YYYY-MM-DD format, converts them to datetime objects, and generates a random date within the range using the random module.
- The
main function demonstrates example usage of both functions.
Note: This implementation uses the hashlib library for hashing and the datetime library for date manipulation. The random library is used to generate random dates within the given range.