Python Date and Time

From Wiki
Jump to navigation Jump to search
# The "time" module is the most basic.
# Date/time values are stored as seconds since 1970-01-01 or as 9-element tuples
# Item  Meaning     Field name  Range       Notes
# 0     Year        tm_year     1970-2038   Wider on some platforms
# 1     Month       tm_mon      1-12        1 is January; 12 is December
# 2     Day         tm_mday     1-31
# 3     Hour        tm_hour     0-23        0 is midnight; 12 is noon
# 4     Minute      tm_min      0-59
# 5     Second      tm_sec      0-61        60 and 61 for leap seconds
# 6     Weekday     tm_wday     0-6         0 is Monday; 6 is Sunday
# 7     Year day    tm_yday     1-366       Day number within the year
# 8     DST flag    tm_isdst    -1 to 1     -1 means library determines DST

import time
# convert string to time tuple
x = time.strptime('2006-04-13', '%Y-%m-%d') # (2006, 4, 13, 0, 0, 0, 3, 103, -1)
x.tm_year                                   # 2006
x.tm_wday                                   # 3 (Thursday)
# convert time tuple to string
time.strftime('%Y-%m-%d', x)                # '2006-04-13'
# convert time tuple to seconds
seconds = time.mktime(x)                    # 1144911600.0
# convert seconds to time tuple
time.localtime(seconds)                     # (2006, 4, 13, 0, 0, 0, 3, 103, 1)
# get current time as tuple
time.localtime()                            # (2006, 6, 16, 10, 2, 3, 4, 167, 1)

Full date format syntax: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Date arithmetic

import datetime
day = datetime.date(2008, 6, 23)
day.isoformat()   # '2008-06-23'
datetime.date.today().isoformat()  # '2011-01-05'
week = datetime.timedelta(days=7)
(day+week).isoformat()  #  '2008-06-30'

yesterday = datetime.date.today() - datetime.timedelta(days=1)

Measuring elapsed time

time.clock()            # returns a float representing some number of seconds

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of "processor time", 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(). The resolution is typically better than one microsecond.


datetime Module

import datetime
t1 = datetime.datetime.strptime("2011-05-10T05:19:47Z", "%Y-%m-%dT%H:%M:%SZ")
t2 = datetime.datetime.strptime("2011-05-10T05:20:06Z", "%Y-%m-%dT%H:%M:%SZ")
elapsed = t2 - t1
print elapsed.seconds