To check if the dates in the column DT_INTERNACAO of a pandas DataFrame happened within the last 30 days or earlier, you can use the following Python code:
python
import pandas as pd
from datetime import datetime, timedelta
# Sample data
data = {
'DT_INTERNACAO': ['2023-03-01', '2023-03-15', '2023-04-05', '2023-02-01']
}
# Create a DataFrame
df = pd.DataFrame(data)
# Convert the DT_INTERNACAO column to datetime
df['DT_INTERNACAO'] = pd.to_datetime(df['DT_INTERNACAO'])
# Get the current date
now = pd.to_datetime('now')
# Calculate the date 30 days ago from the current date
thirty_days_ago = now - timedelta(days=30)
# Check if the dates in DT_INTERNACAO are within the last 30 days or earlier
df['WITHIN_30_DAYS'] = df['DT_INTERNACAO'].apply(lambda x: x <= thirty_days_ago)
print(df)
This code snippet does the following:
Creates a sample pandas DataFrame with a column DT_INTERNACAO containing dates as strings.
Converts the DT_INTERNACAO column to datetime objects.
Calculates the current date and the date 30 days ago.
Applies a lambda function to the DT_INTERNACAO column to check if each date is within the last 30 days or earlier. The result is a new column WITHIN_30_DAYS with Boolean values: True if the date is within the last 30 days or earlier, and False otherwise.
Prints the DataFrame with the new column.
Make sure to adjust the data dictionary to match your actual DataFrame. If you are reading from a CSV file or another source, you would replace the data dictionary with the appropriate pandas read function, like pd.read_csv('your_file.csv').
Also, note that the now variable is set to the current time when the code is run. If you need to account for a specific time zone or have a different reference time, you should adjust the now variable accordingly.