Python 3 — time strptime() method


Suspend execution of the process for the given number of seconds.
Sleep is not affected by system time updates. Sleep is paused during
system suspend. For example, if a process sleeps for 60 seconds and
the system is suspended for 30 seconds in the middle of the sleep, the
sleep duration is 90 seconds in the real time.

Sleep can be interrupted by a signal: the function fails with EINTR.

Name C Resolution
nanosleep() 1 ns
clock_nanosleep() 1 ns
usleep() 1 µs
delay() 1 µs
sleep() 1 sec

Other functions:

Name C Resolution
sigtimedwait() 1 ns
pthread_cond_timedwait() 1 ns
sem_timedwait() 1 ns
select() 1 µs
epoll() 1 ms
poll() 1 ms
WaitForSingleObject() 1 ms

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

  • sleep(seconds)
  • usleep(microseconds)
  • nanosleep(nanoseconds, remaining):
    Linux manpage of nanosleep()
  • delay(milliseconds)

clock_nanosleep(clock_id, flags, nanoseconds, remaining): Linux
manpage of clock_nanosleep().

If flags is TIMER_ABSTIME, then request is interpreted as an absolute
time as measured by the clock, clock_id. If request is less than or
equal to the current value of the clock, then clock_nanosleep()
returns immediately without suspending the calling thread.

POSIX.1 specifies that changing the value of the CLOCK_REALTIME clock
via clock_settime(2) shall have no effect on a thread that is blocked
on a relative clock_nanosleep().

select(nfds, readfds, writefds, exceptfs, timeout).

Since Linux 2.6.28, select() uses high-resolution timers to handle the
timeout. A process has a «slack» attribute to configure the precision
of the timeout, the default slack is 50 microseconds. Before Linux
2.6.28, timeouts for select() were handled by the main timing
subsystem at a jiffy-level resolution. Read also High- (but not too
high-) resolution timeouts and
Timer slack.

  • poll(), epoll()
  • sigtimedwait(). POSIX: «If the Monotonic Clock option is supported,
    the CLOCK_MONOTONIC clock shall be used to measure the time
    interval specified by the timeout argument.»
  • pthread_cond_timedwait(), pthread_condattr_setclock(). «The default
    value of the clock attribute shall refer to the system time.»
  • sem_timedwait(): «If the Timers option is supported, the timeout
    shall be based on the CLOCK_REALTIME clock. If the Timers option is
    not supported, the timeout shall be based on the system time as
    returned by the time() function. The precision of the timeout
    shall be the precision of the clock on which it is based.»
  • WaitForSingleObject(): use the same timer than GetTickCount() with
    the same precision.

Working around operating system bugs?

Should Python ensure that a monotonic clock is truly
monotonic by computing the maximum with the clock value and the
previous value?

Since it’s relatively straightforward to cache the last value returned
using a static variable, it might be interesting to use this to make
sure that the values returned are indeed monotonic.

  • Virtual machines provide less reliable clocks.
  • QueryPerformanceCounter() has known bugs (only one is not fixed yet)

Python may only work around a specific known operating system bug:
KB274323 contains a code example to workaround the bug (use
GetTickCount() to detect QueryPerformanceCounter() leap).

Issues with «correcting» non-monotonicities:

The strftime() Method

The object has a method for formatting date objects into readable strings.

The method is called , and takes one parameter,
, to specify the format of the returned string:


Display the name of the month:

import datetimex = datetime.datetime(2018, 6, 1)print(x.strftime(«%B»))

A reference of all the legal format codes:

Directive Description Example Try it
%a Weekday, short version Wed Try it »
%A Weekday, full version Wednesday Try it »
%w Weekday as a number 0-6, 0 is Sunday 3 Try it »
%d Day of month 01-31 31 Try it »
%b Month name, short version Dec Try it »
%B Month name, full version December Try it »
%m Month as a number 01-12 12 Try it »
%y Year, short version, without century 18 Try it »
%Y Year, full version 2018 Try it »
%H Hour 00-23 17 Try it »
%I Hour 00-12 05 Try it »
%p AM/PM PM Try it »
%M Minute 00-59 41 Try it »
%S Second 00-59 08 Try it »
%f Microsecond 000000-999999 548513 Try it »
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365 Try it »
%U Week number of year, Sunday as the first day of week, 00-53 52 Try it »
%W Week number of year, Monday as the first day of week, 00-53 52 Try it »
%c Local version of date and time Mon Dec 31 17:41:00 2018 Try it »
%x Local version of date 12/31/18 Try it »
%X Local version of time 17:41:00 Try it »
%% A % character % Try it »

❮ Previous
Next ❯


  • %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

Introduction : datetime module

  1. datetime
  2. date
  3. time
  4. timedelta

People who have no experience of working with real-world datasets might have not encountered date columns. They might be under impression that working with dates is rarely used and not so important. To enlighten them, I have listed down real-world examples wherein using datetime module can be beneficial.

  1. Selecting all the saving account holders who were active on 30th June, 2018 and checking their status whether they are still active
  2. Identifying insureds who filed more than 20 claims in the last 3 months
  3. Identifying customers who made multiple transactions in the last 6 months
  4. Extracting dates from timestamp values

Import datetime module

import datetime

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()",
  • 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
  • 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

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

Pseudo-code :

if == 'nt':
    # GetTickCount64() requires Windows Vista, Server 2008 or later
    if hasattr(_time, 'GetTickCount64'):
        def monotonic():
            return _time.GetTickCount64() * 1e-3
        def monotonic():
            ticks = _time.GetTickCount()
            if ticks < monotonic.last:
                # Integer overflow detected
       += 2**32
            monotonic.last = ticks
            return (ticks + * 1e-3
        monotonic.last = 0 = 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.


if == '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:
            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
            return time.monotonic()
        except OSError:
            perf_counter.use_monotonic = False
    return time.time()
perf_counter.use_performance_counter = ( == 'nt')
perf_counter.use_monotonic = hasattr(time, 'monotonic')

Variant 2: Python strftime() with pre-defined timestamp

It so happens at times, that we need to display the timestamp of the historical datasets. The same can be performed using Python strftime() function.

The method is used to fetch the predefined timestamp. Further, strftime() function can be used to represent it in a standard form using various format codes, as explained above.




from datetime import datetime

given_timestamp = 124579923 
timestamp = datetime.fromtimestamp(given_timestamp)
tym = timestamp.strftime("%H:%M:%S")
date = timestamp.strftime("%d-%m-%Y")
print("Time according to the given timestamp:",tym)
print("Date according to the given timestamp:",date)


Time according to the given timestamp: 03:02:03
Date according to the given timestamp: 13-12-1973


Output, 7, 19)


Customize Date Formats


Other popular format codes

  • returns the first three letter of the weekday
  • returns the complete name of the weekday
  • returns the first three letters of the month
  • returns the complete name of the month

dt.strftime("%b %d, %Y")
Oct 20, 2019

dt.strftime("%B %d, %Y")
October 20, 2019

dt.strftime("%a %B %d, %Y")
Sun October 20, 2019

dt.strftime("%A %B %d, %Y")
Sunday October 20, 2019

dt.strftime("%A, %B %d, %Y")
Sunday, October 20, 2019

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:

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

Examples of clock resolution on x86_64:

Name Operating system OS Resolution Python Resolution
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
The «Python Resolution» is the smallest difference between two calls
to the time function computed in Python using the


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.

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
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *