Treat your password like your toothbrush. Don’t let anybody else use it, and get a new one every six months.

Managing time with Python

In this post, you will learn about managing time time with Python


Although this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may be helpful to consult the platform documentation because these functions’ semantics vary among platforms.

Manage time with the python time module represents time in code, such as objects, numbers, and strings. However, it also provides functionality other than representing time, like waiting during code execution and measuring the efficiency of your code.

By the end of this article, you’ll be able to:

  • Understand core concepts at the heart of working with dates and times, such as epochs, time zones, and daylight savings time
  • Represent time in code using floats, tuples, and struct_time
  • Convert between different time representations
  • Suspend thread execution
  • Measure code performance using perf_counter()

Managing time with Python

There is a popular time module available in Python which provides functions for working with times and for converting between representations. The function time.time() returns the current system time in ticks since 00:00:00 hrs January 1, 1970(epoch).

import time
unixcop = time.time()
print ("Time for UnixCop", unixcop)


Time for UnixCop 1659539923.064521

Getting current time

To translate a time instantly from seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (e.g., local time) that returns a time-tuple with all nine items valid.

import time

unixcoplocaltime = time.localtime(time.time())

print ("Local time for UnixCop", unixcoplocaltime)


Local time for UnixCop time.struct_time(tm_year=2022, tm_mon=8, tm_mday=3, tm_hour=23, tm_min=26, tm_sec=48, tm_wday=2, tm_yday=215, tm_isdst=0)

Getting formatted time

You can format any time as per your requirement, but a simple method to get time in a readable format is asctime() −

import time

unixcoplocaltime = time.asctime(time.localtime(time.time())

print ("Local time for UnixCop", unixcoplocaltime)


Local time for UnixCop Wed Aug  3 23:36:52 2022

Getting a calendar for a month

The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month ( Aug 2022 ) −

import calendar

cal = calendar.month(2022, 8)

print ("Whats the Date", cal)

Whats the Date     August 2022
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31


Please enter your comment!
Please enter your name here

Latest articles

Join us on Facebook