Skip to content

Instantly share code, notes, and snippets.

@juftin
Created September 5, 2020 20:49
Show Gist options
  • Save juftin/7c80dad50573be0125d08054f174425c to your computer and use it in GitHub Desktop.
Save juftin/7c80dad50573be0125d08054f174425c to your computer and use it in GitHub Desktop.
Python: Retrieve Percent Through Month
#!/usr/bin/env python3
# Author:: Justin Flannery (mailto:juftin@juftin.com)
"""
An Easy Script for Retrieving the Percent Through the Current Month
"""
from calendar import monthrange
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
def percent_through_month(timestamp: datetime = None) -> float:
"""
Given a datetime object, return the percent through month progress.
Defaults to datetime.now()
Parameters
----------
timestamp : datetime
Datetime object
Returns
-------
month_completion_percentage: float
"""
if timestamp is None:
timestamp = datetime.now()
beginning_of_month = datetime(year=timestamp.year,
month=timestamp.month,
day=1)
end_of_month = datetime(year=timestamp.year,
month=timestamp.month,
day=monthrange(year=timestamp.year,
month=timestamp.month)[1],
hour=23, minute=59, second=59, microsecond=999999)
seconds_in_month = (end_of_month - beginning_of_month).total_seconds()
current_seconds_through_month = (timestamp - beginning_of_month).total_seconds()
month_completion_percentage = current_seconds_through_month / seconds_in_month
return month_completion_percentage
if __name__ == "__main__":
logging.basicConfig(format="%(asctime)s [%(levelname)8s]: %(message)s [%(name)s]",
handlers=[logging.StreamHandler()],
level=logging.DEBUG
)
ptm = percent_through_month()
logger.info(f"Percent Through Month: {ptm}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment