Most Useful Python Functions For The Python Developers

Hello Learners…

Welcome to my blog…

Table Of Contents

  • Introduction
  • Requirements
  • Get The Date And Time In Python
  • Delete Files And Directory In Python
  • Get File Size And Directory Size With Python
  • Summary
  • References

Introduction

In this post, We implement the Most Useful Python Functions For Python Developers.

These all Functions are implemented for the help to the python Developers.

If we are working on any data science or machine learning or any other project then we can use all the functions that will help us to simplify the process of our project.

Requirements

Python Programming

  • Basic Knowledge Of Python Programming
  • Knowledge Of Python Functions

Here We used ‘try and except‘ block in every function which is good practice for the developers when working with functions.

Most Useful Python Functions For The Python Developers

Get The Date And Time In Python

When we are working on any project then first we need the Date and Time For many purposes.

Here are some functions which return Date and Time that we can use.

getDate()

getDate() functions which return date in MM-DD-YYYY format. The data type of the date_now variable is ‘str‘.

from datetime import datetime

def getDate():
    try:
        date_now=datetime.now().date().strftime("%m-%d-%Y")

        return date_now
    except Exception as e:
        return str(e)

print(getDate())

The Output of the above code snippet.

04-29-2023

getTime()

getTime() functions which return time in HH:MM: SS format. The data type of the time_now variable is str.

from datetime import datetime

def getTime():
    try:
        time_now=datetime.now().time().strftime("%H:%M:%S")
        return time_now
    except Exception as e:
        return str(e)
    
    
print(getTime())

The Output of the above code snippet.

11:06:32

TimeDiff()

Calculate Time Difference

TimeDiff() functions take start time and end time as parameters and return the difference between both given input times. So we can improve the response time of our API by calculating the start time and end time of an API.

from datetime import datetime

def TimeDiff(startTime,lastTime):
  
    start_time = datetime.strptime(startTime, "%H:%M:%S")

    last_time = datetime.strptime(lastTime, "%H:%M:%S")
    delta = last_time - start_time
    sec = delta.total_seconds()
    min = sec / 60
    if min<0:
        return "Start time is greater than end time"

    return min

Let’s understand the work of the above function by an example.

start_time="03:26:58"
end_time="03:54:58"
print(TimeDiff(start_time,end_time))

Here we give the start_time and end_time as parameters to TimeDiff() function.

The Output of the above code snippet.

28.0

This function returns the value of minutes and the datatype of minutes is ‘float’.

Delete Files And Directory In Python

delete_files()

Here we see the delete_files() function. Using this function we can delete any file like txt, jpg, png, py, etc.

This function does not delete directories. It works with only files.

Here we used an os module that can interact with our operating systems and help us to get things done at the operating system level. This function takes the path of the files as a parameter.

import os

def delete_files(filepath):
    try:
        os.remove(filepath)
        return True
    except Exception as e:
        return {"exception":str(e)}

delete_directory()

Remove Empty Directory In Python

Here are the functions for the remove empty directories. Using these functions we can remove only empty directories.

NOTE: This function does not work for Non-Empty Directories.

import os
def delete_directory(dirpath):
    try:
        os.removedirs(dirpath)
        return True
    except Exception as e:
        return {"exception":str(e)}
import os
def delete_directory(dirpath):
    try:
        os.rmdir(dirpath)
        return True
    except Exception as e:
        return {"exception":str(e)}

remove_directory()

Remove Non-Empty Directory In Python

To remove the non-empty directory we have to use the shutil module of Python.

It will remove all the files and directories from the given path of the directory.

import shutil

def remove_directory(dirpath):
    try:

        shutil.rmtree(dirpath)
        return True
    except Exception as e:
        return {"Exception":str(e)}

Get File Size And Directory Size With Python

Get The Size Of The Files

Here we use an os module of Python programming language. It helps us to interact with our operating system and do some operations on the OS leve.

import os

def get_size(file_path):
    try:
        size_kb=os.path.getsize(filename=file_path)/1024
        return size_kb
    except Exception as e:
        return {"Exception":str(e)}

This function return of the file size in KB. This function helps us to get the size of any file, we just need the pass the path of a file.

Continue Adding…

Summary

So These are some of the most common Python programs or functions that we can use in our projects. These functions give some important value to our projects.

Please refer to my other post,

References

Leave a Comment