b7d790f6fe1331004bda260bc91bbce80210be1a
compute/data-munging.md
| ... | ... | @@ -37,3 +37,50 @@ t = datetime.utcfromtimestamp(now) |
| 37 | 37 | lt = utc.localize(t).astimezone(london) |
| 38 | 38 | print(lt.strftime('%Y-%m-%d %H:%M:%S %Z')) |
| 39 | 39 | ``` |
| 40 | + |
|
| 41 | +### Previous calendar month maths in python |
|
| 42 | +``` |
|
| 43 | +import calendar |
|
| 44 | +from datetime import datetime, timedelta |
|
| 45 | + |
|
| 46 | +def prev_month_name(): |
|
| 47 | + today = datetime.today().date() |
|
| 48 | + first_day_this_month = today.replace(day=1) |
|
| 49 | + last_day_prev_month = first_day_this_month - timedelta(days=1) |
|
| 50 | + return calendar.month_name[last_day_prev_month.month] |
|
| 51 | + |
|
| 52 | +def prev_month_year(): |
|
| 53 | + today = datetime.today().date() |
|
| 54 | + first_day_this_month = today.replace(day=1) |
|
| 55 | + last_day_prev_month = first_day_this_month - timedelta(days=1) |
|
| 56 | + return last_day_prev_month.year |
|
| 57 | + |
|
| 58 | +def prev_month_start_epoch(): |
|
| 59 | + today = datetime.today().date() |
|
| 60 | + first_day_this_month = today.replace(day=1) |
|
| 61 | + last_day_prev_month = first_day_this_month - timedelta(days=1) |
|
| 62 | + first_day_prev_month = last_day_prev_month.replace(day=1) |
|
| 63 | + first_day_prev_month_zero_seconds = datetime( |
|
| 64 | + first_day_prev_month.year, |
|
| 65 | + first_day_prev_month.month, |
|
| 66 | + first_day_prev_month.day, |
|
| 67 | + 0, |
|
| 68 | + 0, |
|
| 69 | + 0, |
|
| 70 | + ) |
|
| 71 | + return (first_day_prev_month_zero_seconds - datetime(1970, 1, 1)).total_seconds() |
|
| 72 | + |
|
| 73 | +def prev_month_end_epoch(): |
|
| 74 | + today = datetime.today().date() |
|
| 75 | + first_day_this_month = today.replace(day=1) |
|
| 76 | + last_day_prev_month = first_day_this_month - timedelta(days=1) |
|
| 77 | + last_day_prev_month_midnightish = datetime( |
|
| 78 | + last_day_prev_month.year, |
|
| 79 | + last_day_prev_month.month, |
|
| 80 | + last_day_prev_month.day, |
|
| 81 | + 23, |
|
| 82 | + 59, |
|
| 83 | + 59, |
|
| 84 | + ) |
|
| 85 | + return (last_day_prev_month_midnightish - datetime(1970, 1, 1)).total_seconds() + 1 |
|
| 86 | +``` |