Python does not offer a builtin data type for time like some other languages. However, it provides a couple of standard library modules for just this purpose. The time module is the most primary and basic of such modules.

The time module provide basic functions for interpreting and manipulating time. Before we dive in to how these functions work, it will be vital to first understand how time is represented in Python. 

Understanding the epoch

Literally speaking, time is represented as a float value containing the number of seconds since  January 1st, 1970 at 00:00:00 UTC. This date is referred to as the epoch, it acts as an absolute timestamp and thus not affected by whatever timezone is in use. 

When we speak about a certain point in time, we are referring to the number of seconds from the  the epoch up to that particular time.

Wall clock time

The time() function in the module, basically returns a floating point value representing the number of seconds since the start of the epoch up to the current moment.

#import the time module
import time

#print the number of seconds from the epoch upro now.
print(time.time())

While the value returned by time() can be useful especially for storing and comparing dates, it is not a human-readable date. To convert the seconds  into a more human friendly format, we use the ctime() function.

ctime(seconds = None)

The seconds argument  is the seconds to be converted, if it is not given, current time will be returned. The function converts the input seconds in to a human-readable string in local time.

import time 

#print current time
print("The time is ", time.ctime())

#print what time it will be one hour from now
later = time.time() + 3600
print("In one hour, the time will be ", time.ctime(later) )

Time Components

A human-readable time is made up of various components such as year, month, day, hour, minutes and so on. The functions we have seen so far, do not allow us to access individual attributes of time in a given point from the epoch.

The struct_time() class in the module stores time broken into the core units, this makes it easy to access individual components of the represented  time.

struct_object contains the following attributes related to the time it represents:

Attribute name Description
tm_year year
tm_mon month
tm_mday month day
tm_hour hour
tm_min minute
tm_sec second
tm_wday day of week
tm-yday day of year
tm_sdst daylight saving

To instantiate a struct_object you will have to provide as an argument a tuple containing all the nine elements. Two functions does this for us, the localtime() and the gmtime() functions.

The localtime() function
import time

time_obj = time.localtime()
print(time_obj)

print("year: ", time_obj.tm_year)
print("month: ", time_obj.tm_mon)
print("day", time_obj.tm_mday)
print("hour: ", time_obj.tm_hour)
print("min: ", time_obj.tm_min)
print("sec: ", time_obj.tm_sec)

The localtime() function returns a struct_time object representing the local time with the current timezone applied.

localtime(seconds = None)

The seconds argument represent the seconds from the epoch to be converted to a struct_time, if it is not given, the current time is used.

import time

tomorrow = time.localtime(time.time() + 86400 )
print(tomorrow, '\n')

print("year: ", tomorrow.tm_year)
print("month: ", tomorrow.tm_mon)
print("day", tomorrow.tm_mday)
print("hour: ", tomorrow.tm_hour)
print("min: ", tomorrow.tm_min)
print("sec: ", tomorrow.tm_sec)
The gmtime() function

The gmtime() returns a struct_time object for the input time in GMT/UTC time .

gmtime(seconds = None)
import time

time_obj = time.gmtime()
print(time_obj)

print("year: ", time_obj.tm_year)
print("month: ", time_obj.tm_mon)
print("day", time_obj.tm_mday)
print("hour: ", time_obj.tm_hour)
print("min: ", time_obj.tm_min)
print("sec: ", time_obj.tm_sec)

Working with timezones

Some of the functions in the time module needs the timezone set  in order to function properly. For example, the localtime() function uses the timezone setting to convert a time value into a local time.

In most cases the timezone is automatically set by the system depending on your current geographical location. Sometimes, however, we may need to manually set the timezone ourselves. 

The time module contains some timezone related variables that allows us to get information about the current timezone.

show timezone info

import time

def tzinfo():
    print("zone: ", (time.timezone, (time.timezone / 3600)))
    print("tzname: ", time.tzname)
    print("dst: ", time.daylight)
    print("time: ", time.ctime())

tzinfo()
changing the timezone

To change the default  timezone, we can alter the TZ system variable by setting it to our new timezone value.

changing the default timezone

import os

os.environ["TZ"] = "Europe/Paris"

Parsing and formatting time

We can convert the time between struct_time and string representation using the strptime() and strftime() functions. 

The strptime() function can converts a string to a struct_time object.

strptime(string, format = None)

Convert a string to a struct_time object

import time

now = time.ctime()
print(now, '\n')

time_obj = time.strptime(now)
print(time_obj)

The strftime() object, on the other hand, converts a struct_time object to a string representation.

strftime(format, t = None)

The format parameter is a string that contains one or more conversion specifications. The t parameter is an optional struct_time representing a time stamp, if it's not provided, the current system time is used.

Convert a struct_time object to a formatted string

import time

time_obj = time.localtime()
print(time_obj, end = "\n\n")

# convert struct_time to string
time_string =  time.strftime('%Y/%m/%d %H:%M:%S', time_obj)

print(time_string)

The following table summarizes some of the formatting parameters. 

parameter description
%a Abbreviated weekday name
%A Full weekday name
%b Abbreviated month name
%B Full month name
%d The day of the month [0, 31]
%H Hour (24-hour clock) as a decimal number [00,23]
%I Hour (12-hour clock) as a decimal number [01,12]
%j Day of the year as a decimal number [001,366]
%m Month as a decimal number [01,12]
%M Minute as a decimal number [00,59]
%p Locale’s equivalent of either AM or PM
%S Second as a decimal number [00,61]
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]
%w Weekday as a decimal number [0(Sunday),6]
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]
%x Date representation.
%X Time representation.
%y Year without century, [00 - 99]
%Y Year with century as a decimal number
%z UTC offset in the form +HHMM or -HHMM
%Z Timezone name.

time formatting example

import time

#Today's date as a string
today = time.localtime()

formatted_date = time.strftime("%d %b %Y  %I:%M:%S %p", today)
print(formatted_date)