"""Utils about time""" import calendar from datetime import datetime, timedelta, timezone def get_month_from_timestamp(timestamp: float) -> str: """Get month from timestamp month format: 2021/01 """ ts_datetime = datetime.fromtimestamp(timestamp, tz=timezone.utc) return f"{ts_datetime.year}/{ts_datetime.month}" def get_total_minutes_of_month(timestamp: float) -> int: """Get total minutes of this month""" ts_datetime = datetime.fromtimestamp(timestamp, tz=timezone.utc) _, ndays = calendar.monthrange(ts_datetime.year, ts_datetime.month) return ndays * 24 * 60 def get_month_begin_end_ts(month: str) -> tuple[float, float]: """Get begin and end timestamp of the month 1. If month is not provided, use the current month 2. If the current month is different from the month of an hour ago, use the month of an hour ago 3. If the month is provided, use the month Parameters ---------- month: str The month in the format of "2021/01" Returns ------- tuple[float, float] The begin and end timestamp of the month """ if month == "": current = datetime.now(timezone.utc) hour_ago = current - timedelta(hours=1) if current.month != hour_ago.month: # handle the data of last month current = hour_ago month = current.strftime("%Y/%m") month_datetime = datetime.strptime(month, "%Y/%m").replace(tzinfo=timezone.utc) _, last_day = calendar.monthrange(month_datetime.year, month_datetime.month) begin_ts = month_datetime.replace(day=1, hour=0, minute=0, second=0).timestamp() end_ts = month_datetime.replace( day=last_day, hour=23, minute=59, second=59 ).timestamp() return begin_ts, end_ts def get_date_from_timestamp(timestamp: float) -> str: """Get date from timestamp date format: 2021-01-01 """ ts_datetime = datetime.fromtimestamp(timestamp, tz=timezone.utc) return f"{ts_datetime.year}-{ts_datetime.month}-{ts_datetime.day}"