skip to Main Content

Im trying to create a script where it delete all the file in the blob when the creation date of the file > 15 days. i’m able to delete the blob using the code below but i coudn’t find a way to access creation date from azure and then delete the file

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
storage_account_key = "KEY"
storage_account_name = "STORAGE NAME"
connection_string = "connection STRING "
container_name = "Connection String"
blob_name="blob storage
container_client = ContainerClient.from_connection_string(conn_str=connection_string, 
container_name=container_name)
container_client.delete_blob(blob=blob_name)

2

Answers


  1. What you need to do is get the blob properties using BlobClient.get_blob_properties() method. Once you get the properties, you can find the blob’s created date/time in creation_time property.

    Your code would be something like:

    from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
    storage_account_key = "KEY"
    storage_account_name = "STORAGE NAME"
    connection_string = "connection STRING "
    container_name = "Connection String"
    blob_name="blob storage
    container_client = ContainerClient.from_connection_string(conn_str=connection_string, 
    container_name=container_name)
    blob_client = container_client.get_blob_client(blob=blob_name)
    blob_properties = blob_client.get_blob_properties()
    #Check for creation time and then delete blob if needed
    if blob_properties.creation_time > 'some date time value'
      blob_client.delete_blob()
    
    Login or Signup to reply.
  2. Adding to @Gaurav Mantri, Below is the code where you can check if the creation date is greater than 15 days and delete if it is.

    blob_client = container_client.get_blob_client(blob=blob_name)
    
    blob_properties = blob_client.get_blob_properties()
    
    creation_time=str(blob_properties.creation_time)
    d1 = creation_time[0:creation_time.index(" ")]
    today = str(datetime.today())
    d2 = creation_time[0:today.index(" ")]
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    Threshold=abs((d2 - d1).days)
    
    if Threshold==0:
        blob_client.delete_blob()
        print(blob_name +" got deleted")
    

    RESULTS:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search