Python strptime()

Introduction

The International Standard for the representation of dates and times is ISO 8601. Its full reference number is ISO 8601 : 1988 (E), and its title is «Data elements and interchange formats — Information interchange — Representation of dates and times». A discussion of ISO 8601 has been written by Markus Kuhn.

ISO 8601 describes a large number of date/time formats. For example it defines Basic Format, without punctuation, and Extended Format, with punctuation, and it allows elements to be omitted. This profile defines a restricted range of formats, all of which are valid ISO 8601 dates and times. The aim is to simplify the use of ISO 8601 in World Wide Web-related standards, and to avoid the need for the developers and users of these standards to obtain copies of ISO 8601 itself.

A particular problem with ISO 8601 is that it allows the century to be omitted from years, which is likely to cause trouble as we approach the year 2000. This profile avoids the problem by expressing the year as four digits in all cases.

This profile may be adopted by standards which require an unambiguous representation of dates and times. As different standards have their own requirements regarding granularity and flexibility, this profile offers a number of options. An adopting standard must specify which of these options it permits.

Float type limited to 104 days

The clocks resolution of desktop and laptop computers is getting closer to nanosecond resolution. More and more clocks have a frequency in MHz, up to GHz for the CPU TSC clock.

The Python time.time() function returns the current time as a floating-point number which is usually a 64-bit binary floating-point number (in the IEEE 754 format).

The problem is that the float type starts to lose nanoseconds after 104 days. Converting from nanoseconds (int) to seconds (float) and then back to nanoseconds (int) to check if conversions lose precision:

# no precision loss
>>> x = 2 ** 52 + 1; int(float(x * 1e-9) * 1e9) - x
0
# precision loss! (1 nanosecond)
>>> x = 2 ** 53 + 1; int(float(x * 1e-9) * 1e9) - x
-1
>>> print(datetime.timedelta(seconds=2 ** 53 / 1e9))
104 days, 5:59:59.254741

time.time() returns seconds elapsed since the UNIX epoch: January 1st, 1970. This function hasn’t had nanosecond precision since May 1970 (47 years ago):

Process Time

The process time cannot be set. It is not monotonic: the clocks stop while the process is idle.

Name C Resolution Include Sleep Include Suspend
GetProcessTimes() 100 ns No No
CLOCK_PROCESS_CPUTIME_ID 1 ns No No
getrusage(RUSAGE_SELF) 1 µs No No
times() No No
clock() Yes on Windows, No otherwise No

The «C Resolution» column is the resolution of the underlying C structure.

Examples of clock resolution on x86_64:


Name Operating system OS Resolution Python Resolution
CLOCK_PROCESS_CPUTIME_ID Linux 3.3 1 ns 1 ns
CLOCK_PROF FreeBSD 8.2 10 ms 1 µs
getrusage(RUSAGE_SELF) FreeBSD 8.2 1 µs
getrusage(RUSAGE_SELF) SunOS 5.11 1 µs
CLOCK_PROCESS_CPUTIME_ID Linux 3.0 1 ns 1 µs
getrusage(RUSAGE_SELF) Mac OS 10.6 5 µs
clock() Mac OS 10.6 1 µs 5 µs
CLOCK_PROF OpenBSD 5.0 5 µs
getrusage(RUSAGE_SELF) Linux 3.0 4 ms
getrusage(RUSAGE_SELF) OpenBSD 5.0 8 ms
clock() FreeBSD 8.2 8 ms 8 ms
clock() Linux 3.0 1 µs 10 ms
times() Linux 3.0 10 ms 10 ms
clock() OpenBSD 5.0 10 ms 10 ms
times() OpenBSD 5.0 10 ms 10 ms
times() Mac OS 10.6 10 ms 10 ms
clock() SunOS 5.11 1 µs 10 ms
times() SunOS 5.11 1 µs 10 ms
GetProcessTimes() Windows Seven 16 ms 16 ms
clock() Windows Seven 1 ms 1 ms

The «OS Resolution» is the resolution announced by the operating system. The «Python Resolution» is the smallest difference between two calls to the time function computed in Python using the clock_resolution.py program.

Choosing the clock from a list of constraints

The PEP as proposed offers a few new clocks, but their guarantees are deliberately loose in order to offer useful clocks on different platforms. This inherently embeds policy in the calls, and the caller must thus choose a policy.

The «choose a clock» approach suggests an additional API to let callers implement their own policy if necessary by making most platform clocks available and letting the caller pick amongst them. The PEP’s suggested clocks are still expected to be available for the common simple use cases.

To do this two facilities are needed: an enumeration of clocks, and metadata on the clocks to enable the user to evaluate their suitability.

The primary interface is a function make simple choices easy: the caller can use time.get_clock(*flags) with some combination of flags. This includes at least:

  • time.MONOTONIC: clock cannot go backward
  • time.STEADY: clock rate is steady
  • time.ADJUSTED: clock may be adjusted, for example by NTP
  • time.HIGHRES: clock with the highest resolution

It returns a clock object with a .now() method returning the current time. The clock object is annotated with metadata describing the clock feature set; its .flags field will contain at least all the requested flags.

time.get_clock() returns None if no matching clock is found and so calls can be chained using the or operator. Example of a simple policy decision:

T = get_clock(MONOTONIC) or get_clock(STEADY) or get_clock()
t = T.now()

The available clocks always at least include a wrapper for time.time(), so a final call with no flags can always be used to obtain a working clock.

Examples of flags of system clocks:

  • QueryPerformanceCounter: MONOTONIC | HIGHRES
  • GetTickCount: MONOTONIC | STEADY
  • CLOCK_MONOTONIC: MONOTONIC | STEADY (or only MONOTONIC on Linux)
  • CLOCK_MONOTONIC_RAW: MONOTONIC | STEADY
  • gettimeofday(): (no flag)

The clock objects contain other metadata including the clock flags with additional feature flags above those listed above, the name of the underlying OS facility, and clock precisions.

time.get_clock() still chooses a single clock; an enumeration facility is also required. The most obvious method is to offer time.get_clocks() with the same signature as time.get_clock(), but returning a sequence of all clocks matching the requested flags. Requesting no flags would thus enumerate all available clocks, allowing the caller to make an arbitrary choice amongst them based on their metadata.

Formats

There are several ways to work with time:

format

Python

seconds since the «Epoch»

time.time()

tuple

time.gmtime()

string

time.ctime()

The Epoch is January 1st, 1970, midnight, on UNIX systems. On other systems, look at the results of time.gmtime(0) to discover the date of the Epoch.

Measuring time in seconds since the Epoch is convenient for storage and comparing dates, because you only have a single number to consider.

The tuple contains several values, arranged the following way: year, month 1-12, day 1-31, hour 0-23, minutes 0-59, seconds 0-61, day 0-6 (Mon-Sun), day 1-366, and DST -1,0,+1. «DST» means «daylight savings time.» For more information, see time Module Documentation.

Using a tuple is convenient, because you can access particular numbers by index, and because you can easily compare dates. Remember that Python compares tuple data from front to back. The data is indexed so that comparing tuple times is intuitive.

The string format reads something like «Mon Feb 16 16:04:25 2004». You can’t really compare these usefully, but they’re what you need to display things to the user.

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.

Sr.No. Function & Description
1 time.altzone

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). Use this if the daylight is nonzero.

2 time.asctime()

Accepts a time-tuple and returns a readable 24-character string such as ‘Tue Dec 11 18:07:14 2008’.

3 time.clock( )

Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time().

4 time.ctime()

Like asctime(localtime(secs)) and without arguments is like asctime( )

5 time.gmtime()

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note − t.tm_isdst is always 0

6 time.localtime()

Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).

7 time.mktime(tupletime)

Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch.

8 time.sleep(secs)

Suspends the calling thread for secs seconds.

9 time.strftime(fmt)

Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.

10 time.strptime(str,fmt = ‘%a %b %d %H:%M:%S %Y’)

Parses str according to format string fmt and returns the instant in time-tuple format.

11 time.time( )

Returns the current time instant, a floating-point number of seconds since the epoch.

12 time.tzset()

Resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.

There are two important attributes available with time module. They are −

Sr.No. Attribute & Description
1

time.timezone

Attribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).

2

time.tzname

Attribute time.tzname is a pair of locale-dependent strings, which are the names of the local time zone without and with DST, respectively.

Формат datetime

Представление даты и времени может отличатся в разных странах, организациях и т. д. В США, например, чаще всего используется формат «мм/дд/гггг», тогда как в Великобритании более распространен формат «дд/мм/гггг».

В Python для работы с форматами есть методы и .

Python strftime() — преобразование объекта datetime в строку

Метод определен в классах , и . Он создает форматированную строку из заданного объекта , или .


Пример 16: форматирование даты с использованием метода strftime().

from datetime import datetime

now = datetime.now()

t = now.strftime("%H:%M:%S")
print("time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

Когда вы запустите программу, результат будет примерно таким:

Здесь , , , и т. д. — коды для определения формата. Метод принимает один или несколько кодов и возвращает отформатированную строку на его основе.

В приведенной выше программе переменные , и являются строками.

Основные коды для определения формата:

  • — год
  • — месяц
  • — день
  • — час
  • — минута
  • — секунда

Python strptime()- преобразование строки в  объект datetime

Метод создает объект datetime из заданной строки (представляющей дату и время).

Пример 17: метод strptime().

from datetime import datetime

date_string = "21 June, 2018"
print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

Когда вы запустите программу, вывод будет следующим:

Метод принимает два аргумента:

  1. строка, представляющая дату и время.
  2. формат, определяющий, каким образом части даты и времени расположены в переданной строке.

Кстати, коды , и используются для обозначения дня, месяца (название месяца в полном виде) и года соответственно.

New Functions

Get information on the specified clock. Supported clock names:

  • "clock": time.clock()
  • "monotonic": time.monotonic()
  • "perf_counter": time.perf_counter()
  • "process_time": time.process_time()
  • "time": time.time()

Return a time.clock_info object which has the following attributes:

  • implementation (str): name of the underlying operating system function. Examples: "QueryPerformanceCounter()", "clock_gettime(CLOCK_REALTIME)".
  • monotonic (bool): True if the clock cannot go backward.
  • adjustable (bool): True if the clock can be changed automatically (e.g. by a NTP daemon) or manually by the system administrator, False otherwise
  • resolution (float): resolution in seconds of the clock.

Monotonic clock, i.e. cannot go backward. It is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid and is a number of seconds.

On Windows versions older than Vista, time.monotonic() detects GetTickCount() integer overflow (32 bits, roll-over after 49.7 days). It increases an internal epoch (reference time by) 232 each time that an overflow is detected. The epoch is stored in the process-local state and so the value of time.monotonic() may be different in two Python processes running for more than 49 days. On more recent versions of Windows and on other operating systems, time.monotonic() is system-wide.

Availability: Windows, Mac OS X, Linux, FreeBSD, OpenBSD, Solaris. Not available on GNU/Hurd.

Pseudo-code :

if os.name == 'nt':
    # GetTickCount64() requires Windows Vista, Server 2008 or later
    if hasattr(_time, 'GetTickCount64'):
        def monotonic():
            return _time.GetTickCount64() * 1e-3
    else:
        def monotonic():
            ticks = _time.GetTickCount()
            if ticks < monotonic.last:
                # Integer overflow detected
                monotonic.delta += 2**32
            monotonic.last = ticks
            return (ticks + monotonic.delta) * 1e-3
        monotonic.last = 0
        monotonic.delta = 0

elif sys.platform == 'darwin':
    def monotonic():
        if monotonic.factor is None:
            factor = _time.mach_timebase_info()
            monotonic.factor = timebase / timebase * 1e-9
        return _time.mach_absolute_time() * monotonic.factor
    monotonic.factor = None

elif hasattr(time, "clock_gettime") and hasattr(time, "CLOCK_HIGHRES"):
    def monotonic():
        return time.clock_gettime(time.CLOCK_HIGHRES)

elif hasattr(time, "clock_gettime") and hasattr(time, "CLOCK_MONOTONIC"):
    def monotonic():
        return time.clock_gettime(time.CLOCK_MONOTONIC)

On Windows, QueryPerformanceCounter() is not used even though it has a better resolution than GetTickCount(). It is not reliable and has too many issues.

Performance counter with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid and is a number of seconds.

It is available on all platforms.

Pseudo-code:

if os.name == 'nt':
    def _win_perf_counter():
        if _win_perf_counter.frequency is None:
            _win_perf_counter.frequency = _time.QueryPerformanceFrequency()
        return _time.QueryPerformanceCounter() / _win_perf_counter.frequency
    _win_perf_counter.frequency = None

def perf_counter():
    if perf_counter.use_performance_counter:
        try:
            return _win_perf_counter()
        except OSError:
            # QueryPerformanceFrequency() fails if the installed
            # hardware does not support a high-resolution performance
            # counter
            perf_counter.use_performance_counter = False
    if perf_counter.use_monotonic:
        # The monotonic clock is preferred over the system time
        try:
            return time.monotonic()
        except OSError:
            perf_counter.use_monotonic = False
    return time.time()
perf_counter.use_performance_counter = (os.name == 'nt')
perf_counter.use_monotonic = hasattr(time, 'monotonic')

Parsing ISO 8601 with xml.utils.iso8601

If you have xml.utils.iso8601, you can do the following:

import xml.utils.iso8601
import time

# Present time, in ISO8601
print xml.utils.iso8601.tostring(time.time()) # returns "2004-04-10T04:44:08.19Z"
# From ISO8601 string, to seconds since epoch UTC
print xml.utils.iso8601.parse("2004-04-09T21:39:00-08:00") # -8:00 for Seattle, WA
# The epoch, in ISO8601
print xml.utils.iso8601.ctime() # returns "1969-12-31T16:00-08:00"

The module isn’t perfect; If you omit the dashes, (perfectly valid ISO8601,) you’ll get a ValueError exception. However, unlike time.strptime, xml.utils.iso8601.parse will handle the timezone specification correctly.

xml.utils is distributed in python-xml in debian and ubuntu, but appears to be unmaintained.

mock ISO 8601

You can construct ISO 8601 with the following:

iso_time = time.strftime("%Y-%m-%dT%H:%M:%S", tuple_time)

You can revert the construction with the following:

tuple_time = time.strptime("2004-06-03T00:44:35", "%Y-%m-%dT%H:%M:%S")

The problem with this, though, is that if the string isn’t formatted exactly like that, it won’t be read. For instance, 20040603T00:44:35 is valid ISO8601, as is 20040603 for that matter, but neither will be read by the code above.

To account for both common inputs, you could use:

tuple_time = time.strptime(iso_time.replace("-", ""), "%Y%m%dT%H:%M:%S")

I seem to require receiving both while working with XmlRpc produced by a mix of both Python and Perl code. The XmlRpc specification is not very particular about the ISO8601 variant used for it’s DateTime.

Note that this method does not handle time zones, so trying to parse 2004-06-03T12:34:56-0700 or 2004-06-03T12:34:56Z will fail. This is a fundamental limitation of time.strptime for which there is no easy workaround.

Analysis

The resolution of time.time_ns() is much better than time.time(): 84 ns (2.8x better) vs 239 ns on Linux and 318 us (2.8x better) vs 894 us on Windows. The time.time() resolution will only become larger (worse) as years pass since every day adds 86,400,000,000,000 nanoseconds to the system clock, which increases the precision loss.

The difference between time.perf_counter(), time.monotonic(), time.process_time() and their respective nanosecond variants is not visible in this quick script since the script runs for less than 1 minute, and the uptime of the computer used to run the script was smaller than 1 week. A significant difference may be seen if uptime reaches 104 days or more.

resource.getrusage() and times() have a resolution greater or equal to 1 microsecond, and so don’t need a variant with nanosecond resolution.

Note

Internally, Python starts monotonic() and perf_counter() clocks at zero on some platforms which indirectly reduce the precision loss.

Different types

Many ideas of new types were proposed to support larger or arbitrary precision: fractions, structures or 2-tuple using integers, fixed-point number, etc.

See also the PEP 410 for a previous long discussion on other types.

Adding a new type requires more effort to support it, than reusing the existing int type. The standard library, third party code and applications would have to be modified to support it.

The Python int type is well known, well supported, easy to manipulate, and supports all arithmetic operations such as dt = t2 - t1.

Moreover, taking/returning an integer number of nanoseconds is not a new concept in Python, as witnessed by os.stat_result and os.utime(ns=(atime_ns, mtime_ns)).

Linux clocksource

There were 4 implementations of the time in the Linux kernel: UTIME (1996), timer wheel (1997), HRT (2001) and hrtimers (2007). The latter is the result of the «high-res-timers» project started by George Anzinger in 2001, with contributions by Thomas Gleixner and Douglas Niehaus. The hrtimers implementation was merged into Linux 2.6.21, released in 2007.

hrtimers supports various clock sources. It sets a priority to each source to decide which one will be used. Linux supports the following clock sources:

  • tsc
  • hpet
  • pit
  • pmtmr: ACPI Power Management Timer
  • cyclone

High-resolution timers are not supported on all hardware architectures. They are at least provided on x86/x86_64, ARM and PowerPC.

clock_getres() returns 1 nanosecond for CLOCK_REALTIME and CLOCK_MONOTONIC regardless of underlying clock source. Read Re: clock_getres() and real resolution from Thomas Gleixner (9 Feb 2012) for an explanation.

The /sys/devices/system/clocksource/clocksource0 directory contains two useful files:

  • available_clocksource: list of available clock sources
  • current_clocksource: clock source currently used. It is possible to change the current clocksource by writing the name of a clocksource into this file.

/proc/timer_list contains the list of all hardware timers.

Sub-nanosecond resolution

time.time_ns() API is not theoretically future-proof: if clock resolutions continue to increase below the nanosecond level, new Python functions may be needed.

In practice, the 1 nanosecond resolution is currently enough for all structures returned by all common operating systems functions.

Hardware clocks with a resolution better than 1 nanosecond already exist. For example, the frequency of a CPU TSC clock is the CPU base frequency: the resolution is around 0.3 ns for a CPU running at 3 GHz. Users who have access to such hardware and really need sub-nanosecond resolution can however extend Python for their needs. Such a rare use case doesn’t justify to design the Python standard library to support sub-nanosecond resolution.

For the CPython implementation, nanosecond resolution is convenient: the standard and well supported int64_t type can be used to store a nanosecond-precise timestamp. It supports a timespan of -292 years to +292 years. Using the UNIX epoch as reference, it therefore supports representing times since year 1677 to year 2262:

Existing Functions

The system time which is usually the civil time. It is system-wide by definition. It can be set manually by the system administrator or automatically by a NTP daemon.

It is available on all platforms and cannot fail.

Pseudo-code :

if os.name == "nt":
    def time():
        return _time.GetSystemTimeAsFileTime()
else:
    def time():
        if hasattr(time, "clock_gettime"):
            try:
                return time.clock_gettime(time.CLOCK_REALTIME)
            except OSError:
                # CLOCK_REALTIME is not supported (unlikely)
                pass
        if hasattr(_time, "gettimeofday"):
            try:
                return _time.gettimeofday()
            except OSError:
                # gettimeofday() should not fail
                pass
        if hasattr(_time, "ftime"):
            return _time.ftime()
        else:
            return _time.time()

Directive

  • %a — abbreviated weekday name

  • %A — full weekday name

  • %b — abbreviated month name

  • %B — full month name

  • %c — preferred date and time representation

  • %C — century number (the year divided by 100, range 00 to 99)

  • %d — day of the month (01 to 31)


  • %D — same as %m/%d/%y

  • %e — day of the month (1 to 31)

  • %g — like %G, but without the century

  • %G — 4-digit year corresponding to the ISO week number (see %V).

  • %h — same as %b

  • %H — hour, using a 24-hour clock (00 to 23)

  • %I — hour, using a 12-hour clock (01 to 12)

  • %j — day of the year (001 to 366)

  • %m — month (01 to 12)

  • %M — minute

  • %n — newline character

  • %p — either am or pm according to the given time value

  • %r — time in a.m. and p.m. notation

  • %R — time in 24 hour notation

  • %S — second

  • %t — tab character

  • %T — current time, equal to %H:%M:%S

  • %u — weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1

  • %U — week number of the current year, starting with the first Sunday as the first day of the first week

  • %V — The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week

  • %W — week number of the current year, starting with the first Monday as the first day of the first week

  • %w — day of the week as a decimal, Sunday=0

  • %x — preferred date representation without the time

  • %X — preferred time representation without the date

  • %y — year without a century (range 00 to 99)

  • %Y — year including the century

  • %Z or %z — time zone or name or abbreviation

  • %% — a literal % character

What is TimeTuple?

Many of the Python’s time functions handle time as a tuple of 9 numbers, as shown below −

Index Field Values
4-digit year 2016
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61 (60 or 61 are leap-seconds)
6 Day of Week 0 to 6 (0 is Monday)
7 Day of year 1 to 366 (Julian day)
8 Daylight savings -1, 0, 1, -1 means library determines DST

For Example −

import time

print (time.localtime());

This would produce a result as follows −

time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 9, 
   tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)

The above tuple is equivalent to struct_time structure. This structure has following attributes −

Index Attributes Values
tm_year 2016
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap-seconds)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian day)
8 tm_isdst -1, 0, 1, -1 means library determines DST

Unchanged functions

Since the time.clock() function was deprecated in Python 3.3, no time.clock_ns() is added.

Python has other time-returning functions. No nanosecond variant is proposed for these other functions, either because their internal resolution is greater or equal to 1 us, or because their maximum value is small enough to not lose precision. For example, the maximum value of time.clock_getres() should be 1 second.

Examples of unchanged functions:

  • os module: sched_rr_get_interval(), times(), wait3() and wait4()
  • resource module: ru_utime and ru_stime fields of getrusage()
  • signal module: getitimer(), setitimer()
  • time module: clock_getres()

See also the .

time.monotonic(): Fallback to system time

If no monotonic clock is available, time.monotonic() falls back to the system time.

Issues:

  • It is hard to define such a function correctly in the documentation: is it monotonic? Is it steady? Is it adjusted?
  • Some users want to decide what to do when no monotonic clock is available: use another clock, display an error, or do something else.

Different APIs were proposed to define such function.

  • time.monotonic(fallback=True) falls back to the system time if no monotonic clock is available or if the monotonic clock failed.
  • time.monotonic(fallback=False) raises OSError if monotonic clock fails and NotImplementedError if the system does not provide a monotonic clock

A keyword argument that gets passed as a constant in the caller is usually poor API.

Raising NotImplementedError for a function is something uncommon in Python and should be avoided.

Thread Time

The thread time cannot be set. It is not monotonic: the clocks stop while the thread is idle.

Name C Resolution Include Sleep Include Suspend
CLOCK_THREAD_CPUTIME_ID 1 ns Yes Epoch changes
GetThreadTimes() 100 ns No ?

The «C Resolution» column is the resolution of the underlying C structure.

Examples of clock resolution on x86_64:

Name Operating system OS Resolution Python Resolution
CLOCK_THREAD_CPUTIME_ID FreeBSD 8.2 1 µs 1 µs
CLOCK_THREAD_CPUTIME_ID Linux 3.3 1 ns 649 ns
GetThreadTimes() Windows Seven 16 ms 16 ms

The «OS Resolution» is the resolution announced by the operating system. The «Python Resolution» is the smallest difference between two calls to the time function computed in Python using the clock_resolution.py program.

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/python3
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: 1455508609.34375

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.

The calendar 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 −

Sr.No. Function with Description
1

calendar.calendar(year,w=2,l=1,c=6)

Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. w is the width in characters of each date; each line has length 21*w+18+2*c. l is the number of lines for each week.

2

calendar.firstweekday( )

Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday.

3

calendar.isleap(year)

Returns True if year is a leap year; otherwise, False.

4

calendar.leapdays(y1,y2)

Returns the total number of leap days in the years within range(y1,y2).

5

calendar.month(year,month,w=2,l=1)

Returns a multiline string with a calendar for month month of year year, one line per week plus two header lines. w is the width in characters of each date; each line has length 7*w+6. l is the number of lines for each week.

6

calendar.monthcalendar(year,month)

Returns a list of lists of ints. Each sublist denotes a week. Days outside month month of year year are set to 0; days within the month are set to their day-of-month, 1 and up.

7

calendar.monthrange(year,month)

Returns two integers. The first one is the code of the weekday for the first day of the month month in year year; the second one is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.

8

calendar.prcal(year,w=2,l=1,c=6)

Like print calendar.calendar(year,w,l,c).

9

calendar.prmonth(year,month,w=2,l=1)

Like print calendar.month(year,month,w,l).

10

calendar.setfirstweekday(weekday)

Sets the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday).

11

calendar.timegm(tupletime)

The inverse of time.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.

12

calendar.weekday(year,month,day)

Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).

Performance

Reading a hardware clock has a cost. The following table compares the performance of different hardware clocks on Linux 3.3 with Intel Core i7-2600 at 3.40GHz (8 cores). The bench_time.c program was used to fill these tables.

Function TSC ACPI PM HPET
time() 2 ns 2 ns 2 ns
CLOCK_REALTIME_COARSE 10 ns 10 ns 10 ns
CLOCK_MONOTONIC_COARSE 12 ns 13 ns 12 ns
CLOCK_THREAD_CPUTIME_ID 134 ns 135 ns 135 ns
CLOCK_PROCESS_CPUTIME_ID 127 ns 129 ns 129 ns
clock() 146 ns 146 ns 143 ns
gettimeofday() 23 ns 726 ns 637 ns
CLOCK_MONOTONIC_RAW 31 ns 716 ns 607 ns
CLOCK_REALTIME 27 ns 707 ns 629 ns
CLOCK_MONOTONIC 27 ns 723 ns 635 ns

FreeBSD 8.0 in kvm with hardware virtualization:

Function TSC ACPI-Safe HPET i8254
time() 191 ns 188 ns 189 ns 188 ns
CLOCK_SECOND 187 ns 184 ns 187 ns 183 ns
CLOCK_REALTIME_FAST 189 ns 180 ns 187 ns 190 ns
CLOCK_UPTIME_FAST 191 ns 185 ns 186 ns 196 ns
CLOCK_MONOTONIC_FAST 188 ns 187 ns 188 ns 189 ns
CLOCK_THREAD_CPUTIME_ID 208 ns 206 ns 207 ns 220 ns
CLOCK_VIRTUAL 280 ns 279 ns 283 ns 296 ns
CLOCK_PROF 289 ns 280 ns 282 ns 286 ns
clock() 342 ns 340 ns 337 ns 344 ns
CLOCK_UPTIME_PRECISE 197 ns 10380 ns 4402 ns 4097 ns
CLOCK_REALTIME 196 ns 10376 ns 4337 ns 4054 ns
CLOCK_MONOTONIC_PRECISE 198 ns 10493 ns 4413 ns 3958 ns
CLOCK_UPTIME 197 ns 10523 ns 4458 ns 4058 ns
gettimeofday() 202 ns 10524 ns 4186 ns 3962 ns
CLOCK_REALTIME_PRECISE 197 ns 10599 ns 4394 ns 4060 ns
CLOCK_MONOTONIC 201 ns 10766 ns 4498 ns 3943 ns

Format Code List

The table below shows all the format codes that you can use.

Directive Meaning Example
Abbreviated weekday name. Sun, Mon, …
Full weekday name. Sunday, Monday, …
Weekday as a decimal number. 0, 1, …, 6
Day of the month as a zero-padded decimal. 01, 02, …, 31
Day of the month as a decimal number. 1, 2, …, 30
Abbreviated month name. Jan, Feb, …, Dec
Full month name. January, February, …
Month as a zero-padded decimal number. 01, 02, …, 12
Month as a decimal number. 1, 2, …, 12
Year without century as a zero-padded decimal number. 00, 01, …, 99
Year without century as a decimal number. 0, 1, …, 99
Year with century as a decimal number. 2013, 2019 etc.
Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23
Hour (24-hour clock) as a decimal number. 0, 1, …, 23
Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
Hour (12-hour clock) as a decimal number. 1, 2, … 12
Locale’s AM or PM. AM, PM
Minute as a zero-padded decimal number. 00, 01, …, 59
Minute as a decimal number. 0, 1, …, 59
Second as a zero-padded decimal number. 00, 01, …, 59
Second as a decimal number. 0, 1, …, 59
Microsecond as a decimal number, zero-padded on the left. 000000 — 999999
UTC offset in the form +HHMM or -HHMM.  
Time zone name.  
Day of the year as a zero-padded decimal number. 001, 002, …, 366
Day of the year as a decimal number. 1, 2, …, 366
Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, …, 53
Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, …, 53
Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
Locale’s appropriate date representation. 09/30/13
Locale’s appropriate time representation. 07:06:05
A literal ‘%’ character. %

ValueError in strptime()

If the string (first argument) and the format code (second argument) passed to the doesn’t match, you will get . For example:

If you run this program, you will get an error.

ValueError: time data '12/11/2018' does not match format '%d %m %Y'

Recommended Readings: Python strftime()


С этим читают