Python Time Module With Examples

Posted in /  

Python Time Module With Examples
vinaykhatri

Vinay Khatri
Last updated on May 22, 2024

    Python time module allows you to work with time in Python. It helps you represent time in different formats. Besides, you can perform many other time-related tasks.

    This tutorial explains the Python time module and the different methods available with examples.

    Python Time Module

    time is a standard, built-in module in Python that you need to import into your program if dealing with date and time. It is included in Python's standard utility; hence, there is no need to install it externally. Simply import it into your program using the import keyword.

    The following is the syntax for importing the time module:

    Syntax

    import time

    This module makes it possible to represent time in your program in different formats, like numbers, strings , and objects. This module supports other functionalities: stopping a program from executing for a specific time, gauging code efficiency, and waiting until a program executes.

    Python Time Module Methods

    Let us now explore the different methods available in the time module.

    What is an Epoch?

    An epoch in computer programming is a starting point for dealing with dates and times. It helps you determine the passage of time. It is platform-dependent.

    Now, consider the epoch for your system is March 1, 2010. Let us say today is March 2, 2010, UTC, and you need to measure the time passed since the epoch.

    The epoch will be 86400 seconds. There is only a gap of a day. Hence, the epoch = 24*60*60 = 86400.

    Additionally, the time before the epoch is represented with a negative sign. The epoch for February 28, 2010, UTC, is -86400.

    The epoch for Windows and UNIX systems is January 1, 1970, 00:00:00 UTC .

    1. time.time() - Getting Epoch

    The time.time() method returns the time passed since the epoch in seconds.

    Syntax

    time.time()

    Example

    import time
    epoch_seconds = time.time()
    print('The epoch since Unix was introduced =', epoch_seconds)

    Output

    The epoch since Unix was introduced = 1565364102.1340282

    2. time.ctime() - Receive Time In String from Seconds

    The time.ctime() method returns time in a string type. It takes seconds passed since the epoch as an argument and converts them into a local date and time.

    Syntax

    time.ctime()

    Example

    import time
    epoch_seconds = 1565364102.1340282
    current_time_date = time.ctime(epoch_seconds)
    print("It's",current_time_date)

    Output

    It's Fri Aug  9 20:51:42 2019

    The time.ctime() use the epoch_seconds we provide and convert it into a date and time since the Unix epoch time.

    3. time.sleep() - Delaying the Execution of Programs

    This is a very interesting function of the time module. The time.sleep() method stops the execution of the current thread for the given time period. It accepts seconds as an argument and delays the next output for the same time.

    Read more about time.sleep() method here .

    Syntax

    time.sleep()

    Example

    import datetime
    import time
    print("The first statement prints at",datetime.datetime.now().strftime('minute=%M seconds=%S'))
    time.sleep(5)
    print("The second statement prints at",datetime.datetime.now().strftime('minute=%M seconds=%S'))

    Output

    The first statement prints at minute=20 seconds=07
    The second statement prints at minute=20 seconds=12

    In the above output, we can see a delay of 5 seconds. The first print statement executes at 20 minutes: 7 seconds, and the second statement executes at 20 minutes: 12 seconds.

    time.struct_time() Class

    The time.struct_time() class in Python helps you to access the local time, primarily the non-epochal timestamps. We get the output as the named tuple. We can access the tuple’s value using the index and attribute name.

    The syntax of time.struct_time object is:

    time.struct_time(tm_year=2019, tm_mon=10, tm_mday=10,
    tm_hour=7, tm_min=10, tm_sec=20,
    tm_wday=3, tm_yday=314, tm_isdst=0)

    The following are the attributes of the struct_time object with their values and index:

    Index

    Attribute

    Values

    0

    tm_year

    0000, ...., 2018, ..., 9999

    1

    tm_mon

    1, 2, ..., 12

    2

    tm_mday

    1, 2, ..., 31

    3

    tm_hour

    0, 1, ..., 23

    4

    tm_min

    0, 1, ..., 59

    5

    tm_sec

    0, 1, ..., 61

    6

    tm_wday

    0, 1, ..., 6; Monday is 0

    7

    tm_yday

    1, 2, ..., 366

    8

    tm_isdst

    0, 1 or -1

    The struct_time() class consists of the following methods:

    4. time.localtime()

    The time.localtime() method takes the time passed since the epoch in seconds. It outputs the struct_time() object (a named tuple containing 9 attributes as discussed above) in the local time.

    It is important to note that if you do not specify the seconds parameter as an argument to the time.localtime( ) function, it takes the time returned by the time.time() function.

    Syntax

    time.localtime()

    Example

    import time
    now = time.localtime(1565364102.1340282)
    print("now value is:", now)
    print()
    print("year:", now.tm_year)
    print('month',now.tm_mon)
    print("tm_hour:", now.tm_hour)

    Output

    now value is: time.struct_time(tm_year=2019, tm_mon=8, tm_mday=9, tm_hour=20, tm_min=51, tm_sec=42, tm_wday=4, tm_yday=221, tm_isdst=0)
    year: 2019
    month 8
    tm_hour: 20

    5. time.gmtime()

    The time.gmtime() method in the Python time module accepts the seconds passed since the epoch and represents them in the form of the time.struct_time() object in UTC as output. Here, the tm_isdst attribute is always 0.

    This function takes the output of the time.time() function if you do not specify the seconds parameter.

    Syntax

    time.gmtime()

    Example

    import time
    now = time.gmtime(1565364102.1340282)
    print("now value is:", now)
    print()
    print("year:", now.tm_year)
    print('month',now.tm_mon)
    print("tm_hour:", now.tm_hour)

    Output

    year: 2019
    month 8
    tm_hour: 15

    6. time.mktime()

    This function is the inverse of the time.localtime() function. It accepts the struct_time object (a tuple containing 9 attributes) as an argument and returns the time passed since the epoch in seconds in the local time.

    The following is the structure of the struct_time object:

    (year, month, day, hour, minute, second, weekday, day of the year, daylight saving)

    Syntax

    time.mktime()

    Example

    import time
    import time
    now = 1565364102.1340282
    struct_time_obj = time.localtime(now)
    print("struct_time_obj ", struct_time_obj)
    epoch_seconds = time.mktime(struct_time_obj)
    print("epoch_second: ", epoch_seconds)

    Output

    struct_time_obj  time.struct_time(tm_year=2019, tm_mon=8, tm_mday=9, tm_hour=20, tm_min=51, tm_sec=42, tm_wday=4, tm_yday=221, tm_isdst=0)
    1565364102.0

    7. time.asctime()

    The time.asctime() method returns the time in string format. It accepts struct_time or a corresponding 9-element tuple as an argument obtained by the time.gmtime() or time.localtime() methods. The time in the string format has the following structure:

    Day Mon Date Hour:Min:Sec Year

    Syntax

    time.asctime()

    Example

    import time
    now = 1565364102.1340282
    struct_time_obj = time.localtime(now)
    print("struct_time_obj ", struct_time_obj)
    Date_Time = time.asctime(struct_time_obj)
    print("Date_Time",Date_Time )

    Output

    struct_time_obj  time.struct_time(tm_year=2019, tm_mon=8, tm_mday=9, tm_hour=20, tm_min=51, tm_sec=42, tm_wday=4, tm_yday=221, tm_isdst=0)
    Date_Time Fri Aug  9 20:51:42 2019

    8. time.strftime()

    The time.strftime() takes an argument as the struct_time() object and returns an equivalent string in the format specified in the argument.

    If the time is not specified, the function takes the current local time returned by the time.localtime() function.

    Syntax

    time.strftime()

    Example

    import time
    tuple_structtime = time.localtime() # get struct_time
    string_time = time.strftime("%m/%d/%Y, %H:%M:%S", tuple_structtime)
    print(string_time)

    Output

    05/16/2023, 05:28:49

    Here, %m, %d, %Y, %H, %M, and %S are format codes.

    • %Y - year
    • %m - month
    • %d - day
    • %H - hour
    • %M - minute
    • %S - second

    9. time.strptime()

    The time.strptime() function takes a string representing time as an argument, parses it, and converts it into the struct_time object.

    Syntax

    time.strptime()

    Example

    import time
    time_string = "17 June, 1998"
    result = time.strptime(time_string, "%d %B, %Y")
    print(result)

    Output

    time.struct_time(tm_year=2023, tm_mon=7, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=-1)

    Conclusion

    This was all about the Python time module. It allows us to represent the date and time in Python in different formats. It is an in-built module and does not require any installation. You can directly import it into your program.

    All the above methods help you display the time and date by taking different arguments. We recommend you try the above functions using different inputs and understand how they work. The only thing to understand here is the epoch. Once you know what epoch is, you can use these methods easily.

    If you have any queries regarding this article, let us know in the comments.

    People are also reading:

    Leave a Comment on this Post

    0 Comments