yesterday's date

arkiboys 9,691 Reputation points
2023-03-29T07:38:37.6+00:00

hello,
This is how I get todays date in three parts, year and month and day separately.
Question:
How can I do the same but for yesterday's date? please note the current date could be first of jan and so it needs to show accurately the previous day to be

year=2022

month=12

day=31

thank you

Azure Databricks
Azure Databricks
An Apache Spark-based analytics platform optimized for Azure.
2,163 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Sreeju Nair 12,346 Reputation points
    2023-03-29T08:36:33.38+00:00

    Thank you for asking the question. Azure Databricks supports a vide variety of built-in functions. This include several functions for date manipulation. I recommend you to go through the date functions in Azure Databricks from the below URL.

    https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-functions-builtin#date-timestamp-and-interval-functions

    Basically, you can use the DateAdd Function to add or subtract days from the date. To subtract, pass the argument as negative. More details can be found in the below URL.

    https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/functions/date_add

    Hope this helps

    0 comments No comments

  2. ShaikMaheer-MSFT 38,441 Reputation points Microsoft Employee
    2023-03-29T16:39:15.6466667+00:00

    Hi @arkiboys,

    Thank you for posting query in Microsoft Q&A Platform.

    You can use the datetime module and dateutil library to get the previous date, year and month in PySpark.

    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    
    # Get the previous date
    previous_date = datetime.today() - relativedelta(days=1)
    # Get the previous year
    previous_year = datetime.today() - relativedelta(years=1)
    # Get the previous month
    previous_month = datetime.today() - relativedelta(months=1)
    
    

    Hope this helps. Please let me know if any further queries.


    Please consider hitting Accept Answer button. Accepted answers help community as well.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.