Python : Getting Current Date & Time

Python3 provides

  • datetime module to get the current date and time. The classes provided by the datetime module also have the functionality for manoeuvring the date and time.
  • time module to get the current time.
Module Function Usage
datetime datetime.datetime.now( ) returns current date and time
datetime datetime.datetime.now( ).date( ) returns current date
datetime datetime.datetime.now( ).time( ) returns current time
datetime datetime.datetime.now( ).date( ).strftime("%d-%m-%Y") returns date in the specified format
time time.localtime( ) returns current time
time time.strftime( “%H:%M:%S”, time.localtime( ) ) returns current time
in the specified format

Python3 : Program for getting the current date and time.

import datetime
import time

def Get_Local_Time() :
    time_now = time.strftime("%H:%M:%S", time.localtime())
    return time_now

def Get_Current_Time() :
    time_now = datetime.datetime.now().time()
    return time_now

def Get_Current_Date() :
    date_now = datetime.datetime.now().date()
    return date_now

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

def Get_Current_Date_Time() :
    date_time_now = datetime.datetime.now()
    return date_time_now

def Get_Date_Time_After_N_Days(ndays) :
    time_after_7_days = datetime.datetime.now() + datetime.timedelta(days = ndays)
    return time_after_7_days

def main() :
    print("Current date and time : " + str(Get_Current_Date_Time()))

    print("Current date : " + str(Get_Current_Date()))

    print("Current formatted date : " + str(Get_Current_Formatted_Date()))

    print("Current time : " + str(Get_Current_Time()))

    after = 7
    print("Date and time after 7 days from today : " + str(Get_Date_Time_After_N_Days(after)))

    print("Local time (using time module): " + str(Get_Local_Time()))

if __name__ == "__main__" :
    main()

Output

Current date and time : 2021-10-13 16:18:43.401812
Current date : 2021-10-13
Current formatted date : 13-10-2021
Current time : 16:18:43.401913
Date and time after 7 days from today : 2021-10-20 16:18:43.401930
Local time (using time module): 16:18:43


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.