Search code examples
pythondatedatetimetimedelta

The right way to parse date


Exist an easier way to do this kind of parse date?

I'm trying to make a filter in pandas to localize dates 3 months ago and loc the entire month too.

The code works, but I'm searching for the best way.

final_date = pd.to_datetime(f'{(datetime.today() - timedelta(days=90)).year}-{(datetime.today() - timedelta(days=90)).month}-01', dayfirst=True)

Solution

  • My Suggestion

    This version of the code is more concise and easier to read. It avoids using multiple calls to datetime.today() and string formatting.

    import pandas as pd
    from datetime import date, timedelta
    
    # Calculate the date 90 days ago
    d = date.today() - timedelta(days=90)
    
    # Format the date as a string in the '%Y-%m-01' format
    date_str = d.strftime('%Y-%m-01')
    
    # Parse the string as a datetime object
    final_date = pd.to_datetime(date_str, dayfirst=True)