PYTHON - DATE AND TIMEA Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Python's time and calendar modules help track dates and times. What is Tick? Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch). 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 12:00am, January 1, 1970(epoch). Example
#!/usr/bin/python
import time; # This is required to include time module. ticks = time.time() print "Number of ticks since 12:00am, January 1, 1970:", ticks This would produce a result something as follows:
Number of ticks since 12:00am, January 1, 1970: 7186862.73399
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows. What is TimeTuple? Many of Python's time functions handle time as a tuple of 9 numbers, as shown below:
To translate a time instant from a seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (For example, localtime) that returns a time-tuple with all nine items valid.
#!/usr/bin/python
import time; localtime = time.localtime(time.time()) print "Local current time :", localtime This would produce the following result, which could be formatted in any other presentable form:
Local current time : time.struct_time(tm_year=2013, tm_mon=7,
tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0) Getting Formatted Time You can format any time as per your requirement, but simple method to get time in readable format is asctime():
#!/usr/bin/python
import time; localtime = time.asctime( time.localtime(time.time()) ) print "Local current time :", localtime This would produce the following result:
Local current time : Tue Jan 13 10:17:09 2009
Getting 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 ( Jan 2008 ):
#!/usr/bin/python
import calendar cal = calendar.month(2008, 1) print "Here is the calendar:" print cal; This would produce the following result:
Here is the calendar:
January 2008 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 The time Module There is a popular time module available in Python which provides functions for working with times and for converting between representations. Here is the list of all available methods:
71. time.altzone Description The method altzone()is the attribute of the time module. This returns the offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero. Syntax Following is the syntax for altzone() method:
time.altzone
Parameters NA Return Value This method returns the offset of the local DST timezone, in seconds west of UTC, if one is defined. Example The following example shows the usage of altzone() method.
#!/usr/bin/python
import time print "time.altzone %d " % time.altzone When we run above program, it produces following result:
time.altzone() 25200
72. time.actime([tupletime]) Description The method asctime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'. Syntax Following is the syntax for asctime() method:
time.asctime([t]))
Parameters t -- This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function. Return Value This method returns 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'. Example The following example shows the usage of asctime() method.
#!/usr/bin/python
import time t = time.localtime() print "time.asctime(t): %s " % time.asctime(t) When we run above program, it produces following result:
time.asctime(t): Tue Feb 17 09:42:58 2009
73. time.clock( ) Description The method clock() returns the current processor time as a floating point number expressed in seconds on Unix. The precision depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter. Syntax Following is the syntax for clock() method:
time.clock()
Parameters NA Return Value This method returns the current processor time as a floating point number expressed in seconds on Unix and in Windows it returns wall-clock seconds elapsed since the first call to this function, as a floating point number. Example The following example shows the usage of clock() method.
#!/usr/bin/python
import time def procedure(): time.sleep(2.5) # measure process time t0 = time.clock() procedure() print time.clock() - t0, "seconds process time" # measure wall time t0 = time.time() procedure() print time.time() - t0, "seconds wall time" When we run above program, it produces following result:
0.0 seconds process time
2.50023603439 seconds wall time Note: Not all systems can measure the true process time. On such systems (including Windows), clock usually measures the wall time since the program was started. 74. time.ctime([secs]) Description The method ctime() converts a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. This function is equivalent to asctime(localtime(secs)). Locale information is not used by ctime(). Syntax Following is the syntax for ctime() method:
time.ctime([ sec ])
Parameters
This method does not return any value. Example The following example shows the usage of ctime() method.
#!/usr/bin/python
import time print "time.ctime() : %s" % time.ctime() When we run above program, it produces following result:
time.ctime() : Tue Feb 17 10:00:18 2009
75. time.gmtime([secs]) Description The method gmtime() converts a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. Syntax Following is the syntax for gmtime() method:
time.gmtime([ sec ])
Parameters sec -- These are the number of seconds to be converted into structure struct_time representation. Return Value This method does not return any value. Example The following example shows the usage of gmtime() method.
#!/usr/bin/python
import time print "time.gmtime() : %s" % time.gmtime() When we run above program, it produces following result:
time.gmtime() : (2009, 2, 17, 17, 3, 38, 1, 48, 0)
76. time.localtime([secs]) Description The method localtime() is similar to gmtime() but it converts number of seconds to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time. Syntax Following is the syntax for localtime() method:
time.localtime([ sec ])
Parameters sec -- These are the number of seconds to be converted into structure struct_time representation. Return Value This method does not return any value. Example The following example shows the usage of localtime() method.
#!/usr/bin/python
import time print "time.localtime() : %s" % time.localtime() When we run above program, it produces following result:
time.localtime() : (2009, 2, 17, 17, 3, 38, 1, 48, 0)
77. time.mktime(tupletime) Description The method mktime() is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple and it returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueErrorwill be raised. Syntax Following is the syntax for mktime() method:
time.mktime(t)
Parameters t -- This is the struct_time or full 9-tuple. Return Value This method returns a floating point number, for compatibility with time(). Example The following example shows the usage of mktime() method.
#!/usr/bin/python
import time t = (2009, 2, 17, 17, 3, 38, 1, 48, 0) secs = time.mktime( t ) print "time.mktime(t) : %f" % secs print "asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)) When we run above program, it produces following result:
time.mktime(t) : 1234915418.000000
asctime(localtime(secs)): Tue Feb 17 17:03:38 2009 78. time.sleep(secs) Description The method sleep() suspends execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Syntax Following is the syntax for sleep() method:
time.sleep(t)
Parameters t -- This is the number of seconds execution to be suspended. Return Value This method does not return any value. Example The following example shows the usage of sleep() method.
#!/usr/bin/python
import time print "Start : %s" % time.ctime() time.sleep( 5 ) print "End : %s" % time.ctime() When we run above program, it produces following result:
Start : Tue Feb 17 10:19:18 2009
End : Tue Feb 17 10:19:23 2009 79. time.strftime(fmt[,tupletime]) Description The method strftime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string. An exception ValueError is raised if any field in t is outside of the allowed range. Syntax Following is the syntax for strftime() method:
time.strftime(format[, t])
Parameters
This method does not return any value. Example The following example shows the usage of strftime() method.
#!/usr/bin/python
import time t = (2009, 2, 17, 17, 3, 38, 1, 48, 0) t = time.mktime(t) print time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t)) When we run above program, it produces following result:
Feb 18 2009 00:03:38
80. time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') Description The method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime(). The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised. Syntax Following is the syntax for strptime() method:
time.strptime(string[, format])
Parameters
Directive
This return value is struct_time as returned by gmtime() or localtime(). Example The following example shows the usage of strptime() method.
#!/usr/bin/python
import time struct_time = time.strptime("30 Nov 00", "%d %b %y") print "returned tuple: %s " % struct_time When we run above program, it produces following result:
returned tuple: (2000, 11, 30, 0, 0, 0, 3, 335, -1)
81. time.time( ) Description The method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC. Note: Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. Syntax Following is the syntax for time() method:
time.time()
Parameters NA Return Value This method returns the time as a floating point number expressed in seconds since the epoch, in UTC. Example The following example shows the usage of time() method.
#!/usr/bin/python
import time print "time.time(): %f " % time.time() print time.localtime( time.time() ) print time.asctime( time.localtime(time.time()) ) When we run above program, it produces following result:
time.time(): 1234892919.655932
(2009, 2, 17, 10, 48, 39, 1, 48, 0) Tue Feb 17 10:48:39 2009 82. time.tzset() Description The method tzset() resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done. The standard format of the TZ environment variable is (whitespace added for clarity):
std offset [dst [offset [,start[/time], end[/time]]]]
Following is the syntax for tzset() method:
time.tzset()
Parameters NA Return Value This method does not return any value. Example The following example shows the usage of tzset() method.
#!/usr/bin/python
import time import os os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0' time.tzset() print time.strftime('%X %x %Z') os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0' time.tzset() print time.strftime('%X %x %Z') When we run above program, it produces following result:
13:00:40 02/17/09 EST
05:00:40 02/18/09 AEDT There are following two important attributes available with time module:
The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year. By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call calendar.setfirstweekday() function. Here is a list of functions available with the calendar module:
If you are interested, then here you would find a list of other important modules and functions to play with date & time in Python:
|