[Python] Defining a date from a column in Python

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a table of codes and dates that is continuously growing from another source, e.g.

    Code Name Date
    RM1377 a 30/07/2022
    RM1377 b 30/07/2022
    RM1377 c 30/07/2022
    RM1377 d 30/07/2022
    RM1378 e 07/08/2022
    RM1378 f 07/08/2022
    RM1378 g 07/08/2022
    RM1378 h 07/08/2022

    And I want to be able to enter a code into an input, and then retrieve the date associated with the code, so that I can query on it.

    How can I define DM1377 as always being 30/07/2022, and account for DM1389 potentially being in the table with another date?

    I.e. instead of cruise_date = datetime.date(2022, 7, 30) I imagine it would be something like cruise_date = datetime.date(Voyage_date)

    from traceback import print_tb
    import pandas as pd
    from dateutil.relativedelta import relativedelta
    import datetime

    #voyage_id = input('Voyage ID:')

    # Retrieve the data and assign headers
    df = pd.read_csv("dcl_manifest_20220729.csv", usecols=[0,2,5,6,7,8], names=['Cruise', 'Booking reference', 'First name', 'Last name', 'DoB', 'Cancellation'])
    df[['Cruise', 'Booking reference', 'First name', 'Last name', 'DoB', 'Cancellation']]

    # Convert DoB column to dates
    df["DoB"] = pd.to_datetime(df["DoB"])

    # Define the cruise date
    cruise_date = datetime.date(2022, 7, 30)

    # Calculate 5 years ago to identify under 5s
    years_ago = cruise_date - relativedelta(years=5)

    # Query under 5s and print the output
    u5 = df.query('DoB > @years_ago & Cruise == "DM1377" & Cancellation == "No"')
    print("Number of under 5s: " + str(len(u5.index)))

    Continue reading...

Compartilhe esta Página