Skip to content

Instantly share code, notes, and snippets.

@mrroot5
Created November 23, 2020 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrroot5/b99a4d46fd0f03c4597dd1ae9dc7c8b8 to your computer and use it in GitHub Desktop.
Save mrroot5/b99a4d46fd0f03c4597dd1ae9dc7c8b8 to your computer and use it in GitHub Desktop.
Manipulación de fechas con python. KEYWORDS: python, python dates, python datetime, python dateutil, python timedelata, dates, datetime, dateutil, timedelata

Intro

En este documento se explican diferentes usos para tranasformar e interactuar con fechas.

La documentación original la encontrarás dentro de cada apartado pero está en inglés. Yo te lo explico en Español.

Obtener datos relacionados con la semana

Obtener el número de la semana de un mes para una fecha específica

In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the month starts on a Wednesday, you'll want to add 2 and then do the division. This is all encapsulated in the function below.

Documentación

import datetime
from math import ceil

def week_of_month(datetime_obj=datetime.datetime.now()):
    """
    Devuelve el numero de la semana de un mes para una fecha especifica
    
    :param datetime_obj: un objeto datetime con una fecha concreta o el dia de hoy
    :return: un numero entero con la semana actual dentro del mes
    """

    first_day = dt.replace(day=1)

    dom = dt.day
    adjusted_dom = dom + first_day.weekday()

    return int(ceil(adjusted_dom/7.0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment