STEM

Handy bespoke helper library you can use in your code

In this post, I’m sharing a script loaded with useful functions that you can use in your code with ease for performing a myriad of necessary and critical tasks without the need to write (and rewrite, test and retest) your code. Just import it and call the function(s) you need. This Python helper library provides many ready-made functions for input or string validations and formatting including password, email, phone, date, and time values.

Instead of having to remember the formatting codes, regex, strftime, strptime and many other syntax, you can use the library to get the results you need right away with intuitive API. The functions are made very flexible to meet various needs for different scenarios. The code is compiled to deliver quickest results.

To use, just import the library as you would with any library, and use all its functions in your Python code. The functions are designed to return values and not interfere with the UI or print outputs, and provides all information on return values so you can handle the outputs and return values the way best suitable for your application.

Functions in the library (in alphabetic order):
➜ extract_time_parts()
➜ format_date()
➜ format_phone()
➜ format_time()
➜ get_month_weekday()
➜ get_version()
➜ get_year()
➜ is_valid_email()
➜ is_valid_phone()
➜ validate_password_format()

Functions and purposes (in alphabetic order):

extract_time_parts(time_str):
Extracts the hour, minute, second, and optionally the AM/PM part from a given time string.

The function determines if the given time string is in 12-hour or 24-hour format.
It then extracts the components accordingly.

Args:
time_str (str): The time string to be parsed.
Expected formats: “HH:MM:SS” for 24-hour format or “HH:MM:SS AM/PM” for 12-hour format.

Returns:
tuple:
– If the time string is in 12-hour format, returns (hour, minute, second, am_pm).
– If the time string is in 24-hour format, returns (hour, minute, second).

Raises:
ValueError: If the time string does not match either the 12-hour or 24-hour format.

Works with time strings in either12-hour or 24-hour format.

……………………………………………………………………………………………………

format_date(date_str=None, pattern=”yyyy-mm-dd”):
Formats the date string into various formats based on the provided pattern.

IMPORTANT:
All date strings passed to format_date() MUST be in yyyy-mm-dd format
or datetime functions cannot handle them!

Acceptable patterns:
– “yyyy-mm-dd” -> Reformats to: 2025-03-01 (for March 1, 2025). DEFAULT if pattern is blank or not passed.
– “mm-dd-yyyy” -> Reformats to: 03-01-2025 (for March 1, 2025).
– “mm-dd-yy” -> Reformats to: 03-01-25 (for March 1, 2025).
– “mm-dd” -> Reformats to: 03-01 (for March 1, xxxx).
– “mm-yy” -> Reformats to: 03-25 (for March xx, 2025).
– “mm-yyyy” -> Reformats to: 03-2025 (for March xx, 2025).
– “yyyy/mm/dd” -> Reformats to: 2025/03/01 (for March 1, 2025).
– “mm/dd/yyyy” -> Reformats to: 03/01/2025 (for March 1, 2025).
– “mm/dd/yy” -> Reformats to: 03/01/25 (for March 1, 2025).
– “mm/dd” -> Reformats to: 03/01 (for March 1, xxxx).
– “mm/yy” -> Reformats to: 03/25 (for March xx, 2025).
– “mm/yyyy” -> Reformats to: 03/2025 (for March xx, 2025).
– “yyyy” -> Reformats to: 2025.
– “yy” -> Reformats to: 25.
– “mm” -> Reformats to: 03.

If date_str is blank or None, the current system date is used in yyyy-mm-dd format.

Args:
date_str (str): The date string to be formatted. Must be a valid date string or None.
If None/blank, uses the current system date.
pattern (str): The format pattern for the output date string. If blank or not passed, defaults to “yyyy-mm-dd”.

Returns:
tuple:
– str: Reformatted date string if successful.
– str: None if successful, or an error string if there is an error.

Raises:
ValueError: If the date string does not match the expected format.

Notes:
– Single digits entered for month or day will be zero-padded automatically.
– Do not escape forward slash (‘/’). Only backslashes need to be escaped with double backslashes.

……………………………………………………………………………………………………

format_phone(phone_str, pattern=”()-“):
Formats a 10-digit phone number string into the desired format or pattern and returns it as a string.

Args:
phonestr (str): A 10-character string consisting of numeric characters. If the input contains any non-numeric characters or the length isn’t exactly 10 characters, the function will return an error.

pattern (str): A string specifying the desired format of the phone number. Accepted values are:

“()-“: Formats the phone number as (xxx)xxx-xxxx
“–“: Formats the phone number as xxx-xxx-xxxx
“..”: Formats the phone number as xxx.xxx.xxxx
If an invalid pattern is passed, the function will return an error.

Returns:
(str, None): A tuple containing the formatted phone number as the first value and None as the second value if the formatting was successful.
(None, str): A tuple containing None as the first value and an error string as the second value if there was an error in reformatting.

Raises:
ValueError: If the phone number string is not made of digits or its length is not 10 characters.
ValueError: If the pattern specified is invalid.

……………………………………………………………………………………………………

format_time(time_str=None, use_12_hour_format=True):
Formats a time string to either a 12-hour format (e.g. 2:30:15 PM) or 24-hour format (e.g. 14:30:15) as specified.
Can accept the parameter string as either a 12-hour or 24-hour format.

Args:
time_str (str, optional): The time string in HH:MM:SS format where HH can be either in 12-hour or 24-hour format (e.g., 2 or 14 for 2 PM). If no time string is provided, the current system time is used.

use_12_hour_format (bool, optional): If True, the function converts the time to 12-hour format and returns the new time string. Otherwise, it converts to 24-hour format and returns the new time string.

Returns:
str: The formatted time string in either 12-hour or 24-hour format based on the use_12_hour_format specifier.

Raises:
ValueError: If the time string does not match the expected HH:MM:SS format.

……………………………………………………………………………………………………
get_month_weekday(date_str=None, date_format=”%Y-%m-%d”):
Takes a date string in and returns the full month name (e.g. March) and weekday name (e.g. Thursday) individually. If no date string is specified, uses the current date as input.

Args:
date_str (str, optional): A date string in YYYY-MM-DD format. If no date string is provided, the current date is used.
date_format (str, optional): The format of the input date string. Defaults to “%Y-%m-%d”.

Returns:
(str, str): A tuple containing:
full_month_name (str): The full month name.
weekday_name (str): The full weekday name.

Raises:
ValueError: If the date string does not match the expected format.

……………………………………………………………………………………………………
get_version()
Shows version (and file name) of the helper functions script. This is useful to verify if you’re using the latest version as well as get the helper library’s actual file name.

Args:
None

Returns:
(str, str): A tuple containing:

version (str): The full version string in the format major.minor.maintenance/patch.build/revision.
file_name (str): The file name (without extension) of this script.

……………………………………………………………………………………………………

get_year(date_str=None, date_format=”%Y-%m-%d”):
Takes a date string returns the year part only. This is a simpler version of format_date() if you just need a specific part of the date. If no date string is specified, uses the current date as input.

Args:
date_str (str, optional): A date string in YYYY-MM-DD format. If no date string is provided, the current date is used.
date_format (str, optional): The format of the input date string. Defaults to “%Y-%m-%d”.

Returns:
str: The year part extracted from the date string.

Raises:
ValueError: If the date string does not match the expected format.

……………………………………………………………………………………………………
is_valid_email(emailstr)
This validates (and does not reformat the string) if the input string is in the right format for an email address

Args:
emailstr (str): A string representing the email address to be validated.

Returns:
bool: True if the email address is in the correct format, otherwise False.

Raises:
None

……………………………………………………………………………………………………
is_valid_phone(phonestr)
This validates (and does not reformat the string) if input is in this 10-digit string format: (xxx)xxx-xxxx

Args:
phonestr (str): A string representing the phone number to be validated.

Returns:
bool: True if the phone number is in the correct format, otherwise False.

Raises:
None

……………………………………………………………………………………………………

validate_password_format(password, min_length=8, exclude_list=None):
This validates (and does not reformat the string) if input meets the specified requirements (as arguments) which includes the length of the password, and which special characters are not allowed. The other requirements such as requiring: at least one letter, one number, one upper-case letter, one symbol (or special character) are enforced by default.

Args:
password (str): String containing the password to check for format validity.
min_length (int, optional): Minimum password length. Default is 8 if not specified.
exclude_list (list, optional): List of special characters that are not allowed. If none specified, [‘&’, ‘|’] are disallowed by default.

Returns:
(bool, str or None): A tuple containing:
bool: True if the password format meets all the requirements, otherwise False.
str or None: Error string if there is any error, otherwise None.

Raises:
None


Some Usage Examples

Full set of examples using every function is included with the package in usage_examples.py.

import reformat_validations_tr as rv

Verify if an email address is in valid format:
r = rv.is_valid_email("bad email.com") # returns False
r = rv.is_valid_email("good_email@example.com") # returns True

Format a phone number:
p,error = rv.format_phone("4254444444")
if p: print(p) # p is reformatted correctly and returned as "(425)444-4444"


Format a phone number to a specific format:
p,error = rv.format_phone("4254444444","--") # use a specific pattern
p will contain the formatted phone number as: 425-444-4444
if there was an error, the returned error variable will contain the error message string.

Validate a password format (with minimal parameters passed):
pwd, error = rv.validate_password_format("Password1$")
pwd will be True if it meets password format and strength requirement, otherwise False. If False, error will contain the error message string.

Validate a password format (with optional parameters passed):
pwd, error = rv.validate_password_format("Password1@", 6, "'!','+','%','|'")
Here, we’re specifying the password minimum length must be 6 characters, and it cannot contain any of these characters: ‘!’,’+’,’%’,’|’.
pwd will be True if it meets password format and strength requirement, otherwise False. If False, error will contain the error message string.

Reformat a date: date string and pattern specified
d, error = rv.format_date("1998-3-4","mm/dd/yy")
d will contain reformatted date string as: “03/04/98”

Convert time string to/from 12-hour format/24-hour format:
time_str_12 = "02:30:45 PM"
time_str_24 = "14:30:45"


Extracting components from a 12-hour format time string:
hour, minute, second, am_pm = rv.extract_time_parts(time_str_12)
print(f"12-hour format: {hour}:{minute}:{second} {am_pm}")

Extracting components from 24-hour format time string
hour, minute, second = rv.extract_time_parts(time_str_24)
print(f"24-hour format: {hour}:{minute}:{second}")

and many more. Full set of examples using every function is included with the package in usage_examples.py.

Click here to download the library, along with code examples and full documentation.

See usage_examples.py for examples of how to use them in your code (included in the download package).
See Usage_Agreement.txt for agreement and licensing information (included in the download package).

Back To Top