Python Time Module Examples

In Python, there are three modules to process time, they are time, datetime, and calendar. And time is represented in three ways: a timestamp, a formatted time string, and a structured time. This article will focus on the time module, we will introduce other two modules in later articles.

  1. Timestamp: this is the second after January 1, 1970, such as 1506388236.216345, which can be obtained through time.time() function. A timestamp is a floating point number that can be added or subtracted, but be careful not to let the result exceed the value range.
  2. Formatted time string : this is the time string that we commonly used, such as 2017-09-26 09:12:48, is obtained by time.strftime('% y-% m-%d').
  3. Struct time: a multi-tuple containing the year, month, day, hour, minute and second such as time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=9, tm_min=14, tm_sec=50, tm_wday=1, tm_yday=269, tm_isdst=0) can be obtained through time.localtime() function.

Because Python’s time module implementation primarily calls the C library, each platform may differ. The time module currently only supports until year 2038. If you want to handle dates after year 2038 you should use the datetime module.

1. Formatted Time String.

time. strftime ('% y-% m-%d %H:% m :%S') method can be used to get a formatted time string.

>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2018-11-27 19:13:11'

Note that Spaces, dash lines, and colons are all cosmetic symbols, and that what really controls the string format is the percentile(%). For the formatting control string “% y-% m-%d %H:% m :%S, each letter’s meaning is shown in the list below, note the difference in character case.

  1. %a : Abbreviation of the local week name (Mon for Monday, for example).
  2. %A : The full name of the local week (Monday, for example).
  3. %b : Abbreviation of the local month name (e.g. Agu for August).
  4. %B : The full name of the local month (e.g. August).
  5. %c : A string representation of the local corresponding date and time (e.g. 15/08/27 10:20:06).
  6. %d : Days of the month (01-31) .
  7. %f : Microsecond (range 0.999999) .
  8. %H : Hours of the day (24-hour, 00-23).
  9. %I : Hours (12 hours, 0-11) .
  10. %j : Days of the year (001-366) .
  11. %m : Month (01 – 12).
  12. %M : Minutes (00-59) .
  13. %p : Local am or pm identifiers.
  14. %S : Seconds (00 – 59).
  15. %U : Weeks of the year. ( 00 – 53 ). Sunday is the beginning of a week. All days before the first Sunday are in week 0.
  16. %w : The day of the week (0-6, 0 is Sunday) .
  17. %W : It’s same as %w, except starts on Monday in a week.
  18. %x : Local corresponding date string (e.g. 15/08/01).
  19. %X : Local corresponding time string (e.g. 08:08:10).
  20. %y : Year represented by two numbers( 00 – 99).
  21. %Y : Complete year (4 digits denote year).
  22. %z : Interval with UTC time (return empty string if local time).
  23. %Z : Name of time zone (return empty string if local time).
  24. %% : “%” character.

2. Struct Time.

A structured time tuple can be obtained using methods such as time.localtime().

>>> import time
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=9, tm_mday=26, tm_hour=10, tm_min=6, tm_sec=49

Structured time tuples have nine elements, arranged in order as shown below.

  1. tm_year : Year value such as 2018.
  2. tm_mon : Month value ( 1 – 12).
  3. tm_mday : Day value (1 – 31).
  4. tm_hour : Hour value (0 – 23).
  5. tm_min : Minute value(0 – 59).
  6. tm_sec : Second value(0 – 59).
  7. tm_wday : Weekday ( 0 – 6, 0 means monday).
  8. tm_yday : Day of the year ( 1 – 366 ).
  9. tm_isdst : Whether daylight saving time or not ( The default value is -1 ).

Since structured time is a tuple, it can be evaluated by index, shard, or attribute name. But remember, Python’s time type is immutable, and all time values are read-only and cannot be changed!!

>>>import time 
>>> lt = time.localtime() 
>>> lt 
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=30, tm_hour=19, tm_min=28, tm_sec=29, tm_wday=1, tm_yday=269, tm_isdst=0) 
>>> lt[3] 
19 
>>> lt[2:5] (30, 19, 28) 
>>> lt.tm_yday 
269

Below code change the time value and get an error.

>>> lt.year = 2017
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'time.struct_time' object has no attribute 'year

3. Time Module Methods.

3.1 time.time().

Returns the current system timestamp. You can do arithmetic on the returned timestamp value. This method is often used to calculate the execution time of programs.

>>>import time
>>> 
>>> def func():
... time.sleep(1)
... pass
... 
>>> t1 = time.time()
>>> func()
>>> t2 = time.time()
>>> print(t2 - t1)
1
>>>

3.2 time.localtime([secs]).

Converts a timestamp to the structured time of the current time zone. If the secs parameter is not provided, then use the time.time() to get current timestamp.

>>> import time
>>> time.localtime()
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=27, tm_hour=20, tm_min=23, tm_sec=48, tm_wday=1, tm_yday=331, tm_isdst=0)
>>> time.localtime(1589391888)
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=14, tm_hour=1, tm_min=44, tm_sec=48, tm_wday=3, tm_yday=135, tm_isdst=0)
>>> time.localtime(time.time() + 38000)
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=28, tm_hour=6, tm_min=59, tm_sec=1, tm_wday=2, tm_yday=332, tm_isdst=0)

3.3 time.gmtime([secs]).

Converts a timestamp to the structured time of the UTC time zone. The default value of the optional parameter secs is time.time().

>>> time.gmtime()
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=27, tm_hour=23, tm_min=31, tm_sec=40, tm_wday=1, tm_yday=331, tm_isdst=0)
>>> t = time.time() - 10000
>>> time.gmtime()
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=27, tm_hour=23, tm_min=31, tm_sec=59, tm_wday=1, tm_yday=331, tm_isdst=0)

3.4 time.ctime([secs]).

Convert a timestamp into a formatted string of local time. Default value for the secs parameter is time.time().

>>> time.ctime()
'Wed Nov 28 07:34:35 2018'
>>> time.ctime(time.time())
'Wed Nov 28 07:34:44 2018'
>>> time.ctime(1506691909)
'Fri Sep 29 21:31:49 2017'

3.5 time.asctime([t]).

Convert a structured time to a formatted time string in the format like  Mon Sep 26 18:31:59 2018. The default value for parameter t is time.localtime().

>>> time.asctime()
'Wed Nov 28 08:26:12 2018'
>>> time.asctime(time.localtime())
'Wed Nov 28 08:26:17 2018'
>>> time.asctime(time.gmtime())
'Wed Nov 28 00:26:29 2018'
>>> time.asctime(time.time())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not float

3.6 time.strftime(format [, t]).

Returns the local time represented by the formatted string. Convert a struct_time (such as the return values of time.localtime() and time.gmtime()) into a formatted time string. The first parameter is the time string format.

If t is not specified, time.localtime() is used by default. If any of the elements in the tuple over bounds, an ValueError error is thrown.

>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2018-11-28 08:31:38'
>>> time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())
'2018-11-28 00:31:51'

3.7 time.strptime(string[,format]).

Converts a formatted time string to a structured time. This method is the inverse of the time.strftime() method. The time.strptime() method parses a time string into a time tuple based on the format specified. Note that the string you provide should correspond to the format of the format parameter one by one.

>>> import time
>>> stime = "2018-09-26 12:11:30"
>>> st = time.strptime(stime,"%Y-%m-%d %H:%M:%S")
>>> st
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=26, tm_hour=12, tm_min=11, tm_sec=30, tm_wday=2, tm_yday=269, tm_isdst=-1)
# Below time string format is not correct. 
>>> st = time.strptime(stime,"%Y:%m-%d %H:%M:%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 478, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '2018-09-26 12:11:30' does not match format '%Y:%m-%d %H:%M:%S'

3.8 time.mktime(t).

Converts a structured time into a timestamp. time.mktime() does the opposite of gmtime() and localtime(), which takes struct_time objects as arguments and returns a floating point number representing the time in milliseconds. If the value entered is not a valid time, an OverflowError or ValueError is triggered.

>>> time.mktime(time.localtime())
1543365815.0
>>> time.mktime(1543365815.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not float

3.9 time.clock().

Returns the CPU time to execute the current program. Used to measure the time taken by different programs. This method has different meanings in different operating systems. On Unix systems, it returns “process time,” a floating point number in milliseconds (timestamp). In Windows, the first call returns the actual running time of the process, and the second subsequent call return the duration time since the first call.

>>> import time
>>> t1 = time.clock()
>>> time.sleep(1)
>>> t2 = time.clock()
>>> t3 = t2 - t1
>>> print(t3)
0.000903

3.10 time.sleep(t).

Sleep or pause programs for t seconds, t can be floating point number or integer.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.