Time review

Time as we know is represented by several components, some of which are numerical such as seconds, minutes and hours while others are strings such as timezone, AM and PM. Python provides an arsenal of utilities when dealing with time objects and strings. Therefore, it is relatively easy to get and format the current time in Python.

Get the current time in Python

There are two functions useful for retrieving current time on system. time.gmtime([secs]) converts a time expressed in seconds since the epoch (see this article for an overview on the epoch) to a struct_time in UTC. If the argument secs is not provided or None, the current time as returned by time.time is used.

Similarly, time.localtime([secs]) converts a time expressed in seconds since the epoch to a struct_time in the local timezone. If the argument secs is not provided or None, the current time as returned by time.time is used.

So, what is a time.struct_time object? A time.struct_time object encapsulates all information about one specific time point. It serves as a wrapper to wrap all the relevant information about a time point together so they can be accessed as a unit.

Format the current time in Python

Once we have a time.struct_time object, we can format it into a string so that it can be further processed by another program. We can do so by calling time.strftime(format[, t]) with the current time object as the argument t. If the t argument is not provided or None, then the time_struct object returned by time.localtime is used.

Here's an example:

The format argument accepts a list of directives, which is specified in full at Python's documentation about time. Notice that the last example in the previous code demos a way to convert a time_struct object into a string representation that can be used in a HTTP header.

Get time object in Python from strings

So far, we have covered getting and converting a current time_struct object into a string object. How about the other way around? Luckily, Python provides a function time.strptime that converts a string object into a time_struct object.

Of course, converting back and forth between strings and time_struct objects is easy.

Tips and Suggestions using Python's time module

  • Although Python's time_struct objects are very useful, they are not usable outside of Python's interpreter. A lot of the time, you want to pass the time objects from Python into another language. For example, a Python-based server-side JSON response that includes time_struct objects represented in ISO 8601 format can be processed by client-side Javascript applications which present the time objects in a nice way to end-users.
  • The two functions that convert between time_struct and string objects are easy to remember. time.strftime could be remembered as "string formatted from time" and time.strptime could be remembered as "time represented from string".

About The Author