Mohan pd.
Mohan pd. Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

Comprehensive Python Cheat Sheet for Types | Coders Blog

Comprehensive Python Cheat Sheet for Types | Coders Blog

Here are the Comprehensive cheat sheets for python.

Content

Type
  • Everything is an object.
  • Every object has a type.
  • Type and class are synonymous.
1
2
<type> = type(<el>)                # Or: <el>.__class__
<bool> = isinstance(<el>, <type>)  # Or: issubclass(type(<el>), <type>)
1
2
3
4
>>> type('a'), 'a'.__class__, str

(<class 'str'>, <class 'str'>, <class 'str'>)

Some types do not have builtin names, so they must be imported:

1
from types import FunctionType, MethodType, LambdaType, GeneratorType
ABC

An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().**

1
2
3
4
5
>>> from collections.abc import Sequence, Collection, Iterable
>>> isinstance([1, 2, 3], Iterable)

True
1
2
3
4
5
6
7
+------------------+----------+------------+----------+
|                  | Sequence | Collection | Iterable |
+------------------+----------+------------+----------+
| list, range, str |   yes    |    yes     |   yes    |
| dict, set        |          |    yes     |   yes    |
| iter             |          |            |   yes    |
+------------------+----------+------------+----------+
1
2
3
4
5
>>> from numbers import Integral, Rational, Real, Complex, Number
>>> isinstance(123, Number)

True
1
2
3
4
5
6
7
8
+--------------------+----------+----------+------+---------+--------+
|                    | Integral | Rational | Real | Complex | Number |
+--------------------+----------+----------+------+---------+--------+
| int                |   yes    |   yes    | yes  |   yes   |  yes   |
| fractions.Fraction |          |   yes    | yes  |   yes   |  yes   |
| float              |          |          | yes  |   yes   |  yes   |
| complex            |          |          |      |   yes   |  yes   |
+--------------------+----------+----------+------+---------+--------+
String
1
2
<str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
<str>  = <str>.strip('<chars>')              # Strips all passed characters from both ends.
1
2
3
4
<list> = <str>.split()                       # Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False)    # Splits on line breaks. Keeps them if 'keepends'.
<str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as separator.
1
2
3
4
5
<bool> = <sub_str> in <str>                  # Checks if string contains a substring.
<bool> = <str>.startswith(<sub_str>)         # Pass tuple of strings for multiple options.
<bool> = <str>.endswith(<sub_str>)           # Pass tuple of strings for multiple options.
<int>  = <str>.find(<sub_str>)               # Returns start index of first match or -1.
<int>  = <str>.index(<sub_str>)              # Same but raises ValueError.
1
2
3
<str>  = <str>.replace(old, new [, count])   # Replaces 'old' with 'new' at most 'count' times.
<bool> = <str>.isnumeric()                   # True if str contains only numeric characters.
<list> = textwrap.wrap(<str>, width)         # Nicely breaks string into lines.
  • Also: 'lstrip()' , 'rstrip()' .
  • Also: 'lower()' , 'upper()' , 'capitalize()' and 'title()' .
Char
1
2
<str> = chr(<int>)  # Converts int to unicode char.
<int> = ord(<str>)  # Converts unicode char to int.
1
2
3
4
5
6
7
8
9
10
11
12
>>> ord('0'), ord('9')

(48, 57)

>>> ord('A'), ord('Z')

(65, 90)

>>> ord('a'), ord('z')

(97, 122)
Regex
1
2
3
4
5
6
7
import re
<str>   = re.sub(<regex>, new, text, count=0)  # Substitutes all occurrences.
<list>  = re.findall(<regex>, text)            # Returns all occurrences.
<list>  = re.split(<regex>, text, maxsplit=0)  # Use brackets in regex to keep the matches.
<Match> = re.search(<regex>, text)             # Searches for first occurrence of pattern.
<Match> = re.match(<regex>, text)              # Searches only at the beginning of the text.
<iter>  = re.finditer(<regex>, text)           # Returns all occurrences as match objects.
  • Argument 'flags=re.IGNORECASE' can be used with all functions.
  • Argument 'flags=re.MULTILINE' makes '^' and `‘match the start/end of each line.
  • Argument 'flags=re.DOTALL' makes dot also accept newline.
  • Use r'\1' or '\\1' for backreference.
  • Use '?' to make an operator non-greedy.
Match Object
1
2
3
4
5
<str>   = <Match>.group()   # Whole match. Also group(0).
<str>   = <Match>.group(1)  # Part in first bracket.
<tuple> = <Match>.groups()  # All bracketed parts.
<int>   = <Match>.start()   # Start index of a match.
<int>   = <Match>.end()     # Exclusive end index of a match.
Special Sequences
  • By default digits, whitespaces and alphanumerics from all alphabets are matched, unless 'flags=re.ASCII' argument is used.
  • Use capital letters for negation.
1
2
3
'\d' == '[0-9]'             # Digit
'\s' == '[ \t\n\r\f\v]'     # Whitespace
'\w' == '[a-zA-Z0-9_]'      # Alphanumeric
Format
1
2
<str> = f'{<el_1>}, {<el_2>}'
<str> = '{}, {}'.format(<el_1>, <el_2>)
Attributes
1
2
3
4
5
6
7
8
9
10
11
>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height}'

'187'

>>> '{p.height}'.format(p=person)

'187'

General Options

1
2
3
{<el>:<10}       # '<el>      '
{<el>:^10}       # '   <el>   '
{<el>:>10}       # '      <el>'
1
2
{<el>:.<10}      # '<el>......'
{<el>:>0}        # '<el>'
Strings

** '!r' calls object’s repr() method, instead of str(), to get a string.**

1
2
3
{'abcde'!r:<10}  # "'abcde'   "
{'abcde':.3}     # 'abc'
{'abcde':10.3}   # 'abc       '
Numbers
1
2
3
4
5
6
{ 123456:10,}    # '   123,456'
{ 123456:10_}    # '   123_456'
{ 123456:+10}    # '   +123456'
{-123456:=10}    # '-   123456'
{ 123456: }      # ' 123456'
{-123456: }      # '-123456'
Floats
1
2
3
4
{1.23456:10.3}   # '      1.23'
{1.23456:10.3f}  # '     1.235'
{1.23456:10.3e}  # ' 1.235e+00'
{1.23456:10.3%}  # '  123.456%'
Comparison of float presentation types:
1
2
3
4
5
6
7
8
9
10
11
12
+----------------+----------------+---------------+----------------+-----------------+
|                |    {<float>}   |  {<float>:f}  |   {<float>:e}  |   {<float>:%}   |
+----------------+----------------+---------------+----------------+-----------------+
|    0.000056789 |   '5.6789e-05' |    '0.000057' | '5.678900e-05' |     '0.005679%' |
|    0.00056789  |   '0.00056789' |    '0.000568' | '5.678900e-04' |     '0.056789%' |
|    0.0056789   |   '0.0056789'  |    '0.005679' | '5.678900e-03' |     '0.567890%' |
|    0.056789    |   '0.056789'   |    '0.056789' | '5.678900e-02' |     '5.678900%' |
|    0.56789     |   '0.56789'    |    '0.567890' | '5.678900e-01' |    '56.789000%' |
|    5.6789      |   '5.6789'     |    '5.678900' | '5.678900e+00' |   '567.890000%' |
|   56.789       |  '56.789'      |   '56.789000' | '5.678900e+01' |  '5678.900000%' |
|  567.89        | '567.89'       |  '567.890000' | '5.678900e+02' | '56789.000000%' |
+----------------+----------------+---------------+----------------+-----------------+
1
2
3
4
5
6
7
8
9
10
11
12
+----------------+----------------+---------------+----------------+-----------------+
|                |  {<float>:.2}  | {<float>:.2f} |  {<float>:.2e} |  {<float>:.2%}  |
+----------------+----------------+---------------+----------------+-----------------+
|    0.000056789 |   '5.7e-05'    |      '0.00'   |   '5.68e-05'   |       '0.01%'   |
|    0.00056789  |   '0.00057'    |      '0.00'   |   '5.68e-04'   |       '0.06%'   |
|    0.0056789   |   '0.0057'     |      '0.01'   |   '5.68e-03'   |       '0.57%'   |
|    0.056789    |   '0.057'      |      '0.06'   |   '5.68e-02'   |       '5.68%'   |
|    0.56789     |   '0.57'       |      '0.57'   |   '5.68e-01'   |      '56.79%'   |
|    5.6789      |   '5.7'        |      '5.68'   |   '5.68e+00'   |     '567.89%'   |
|   56.789       |   '5.7e+01'    |     '56.79'   |   '5.68e+01'   |    '5678.90%'   |
|  567.89        |   '5.7e+02'    |    '567.89'   |   '5.68e+02'   |   '56789.00%'   |
+----------------+----------------+---------------+----------------+-----------------+
Ints
1
2
3
{90:c}           # 'Z'
{90:X}           # '5A'
{90:b}           # '1011010'
Numbers
1
2
3
4
<int>      = int(<float/str/bool>)    # Or: math.floor(<float>)
<float>    = float(<int/str/bool>)
<complex>  = complex(real=0, imag=0)  # Or: <real> + <real>j
<Fraction> = fractions.Fraction(numerator=0, denominator=1)
  • ** 'int(<str>)' and 'float(<str>)' raise ‘ValueError’ on malformed strings.**
Basic Functions
1
2
3
4
<num>  = pow(<num>, <num>)            # Or: <num> ** <num>
<real> = abs(<num>)
<int>  = round(<real>)
<real> = round(<real>, ±ndigits)      # `round(126, -1) == 130` 
Math
1
2
3
from math import e, pi, inf, nan
from math import cos, acos, sin, asin, tan, atan, degrees, radians
from math import log, log10, log2
Statistics
1
from statistics import mean, median, variance, pvariance, pstdev
Random
1
2
3
4
5
from random import random, randint, choice, shuffle
<float> = random()
<int>   = randint(from_inclusive, to_inclusive)
<el>    = choice(<list>)
shuffle(<list>)
Bin, Hex
1
2
3
4
<int>     = 0b<bin>            # Or: 0x<hex>
<int>     = int('0b<bin>', 0)  # Or: int('0x<hex>', 0)
<int>     = int('<bin>', 2)    # Or: int('<hex>', 16)
'0b<bin>' = bin(<int>)         # Or: '0x<hex>' = hex(<int>)
Bitwise Operators
1
2
3
4
5
6
<int>     = <int> & <int>      # And
<int>     = <int> | <int>      # Or
<int>     = <int> ^ <int>      # Xor (0 if both bits equal)
<int>     = <int> << n_bits    # Shift left
<int>     = <int> >> n_bits    # Shift right
<int>     = ~<int>             # Compliment (flips bits)
Combinatorics
  • Every function returns an iterator.
  • If you want to print the iterator, you need to pass it to the list() function!
1
from itertools import product, combinations, combinations_with_replacement, permutations
1
2
3
4
5
>>> product([0, 1], repeat=3)

[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
 (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
1
2
3
4
5
>>> product('ab', '12')

[('a', '1'), ('a', '2'),
 ('b', '1'), ('b', '2')]
1
2
3
4
>>> combinations('abc', 2)

[('a', 'b'), ('a', 'c'), ('b', 'c')]
1
2
3
4
5
6
>>> combinations_with_replacement('abc', 2)

[('a', 'a'), ('a', 'b'), ('a', 'c'),
 ('b', 'b'), ('b', 'c'),
 ('c', 'c')]
1
2
3
4
5
6
>>> permutations('abc', 2)

[('a', 'b'), ('a', 'c'),
 ('b', 'a'), ('b', 'c'),
 ('c', 'a'), ('c', 'b')]
Datetime
  • Module ‘datetime’ provides ‘date’ <D> , ‘time’ <T> , ‘datetime’ <DT> and ‘timedelta’ <TD> classes. All are immutable and hashable.
  • Time and datetime can be ‘aware’ <a> , meaning they have defined timezone, or ‘naive’ <n> , meaning they don’t.
  • If object is naive it is presumed to be in system’s timezone.
1
2
from datetime import date, time, datetime, timedelta
from dateutil.tz import UTC, tzlocal, gettz
Constructors
1
2
3
4
5
<D>  = date(year, month, day)
<T>  = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
<DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
<TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
                 minutes=0, hours=0, weeks=0)
  • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
  • ** 'fold=1' means second pass in case of time jumping back for one hour.**
Now
1
2
3
<D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
<DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
<DTa>    = DT.now(<tzinfo>)                 # Aware datetime from current tz time.
  • To extract time use '<DTn>.time()' , '<DTa>.time()' or '<DTa>.timetz()' .
Timezone
1
2
3
<tzinfo> = UTC                              # UTC timezone. London without DST.
<tzinfo> = tzlocal()                        # Local timezone. Also gettz().
<tzinfo> = gettz('<Cont.>/<City>')          # Timezone from 'Continent/City_Name' str.
1
2
<DTa>    = <DT>.astimezone(<tzinfo>)        # Datetime, converted to passed timezone.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>)  # Unconverted object with new timezone.
Encode
1
2
3
4
5
<D/T/DT> = D/T/DT.fromisoformat('<iso>')    # Object from ISO string.
<DT>     = DT.strptime(<str>, '<format>')   # Datetime from str, according to format.
<D/DTn>  = D/DT.fromordinal(<int>)          # D/DTn from days since Christ, at midnight.
<DTn>    = DT.fromtimestamp(<real>)         # Local time DTn from seconds since Epoch.
<DTa>    = DT.fromtimestamp(<real>, <tz.>)  # Aware datetime from seconds since Epoch.
  • ISO strings come in following forms: 'YYYY-MM-DD' , 'HH:MM:SS.ffffff[±<offset>]' , or both separated by 'T' . Offset is formatted as: 'HH:MM' .
  • On Unix systems Epoch is '1970-01-01 00:00 UTC' , '1970-01-01 01:00 CET' , …
Decode
1
2
3
4
5
<str>    = <D/T/DT>.isoformat()             # ISO string representation.
<str>    = <D/T/DT>.strftime('<format>')    # Custom string representation.
<int>    = <D/DT>.toordinal()               # Days since Christ, ignoring time and tz.
<float>  = <DTn>.timestamp()                # Seconds since Epoch from DTn in local time.
<float>  = <DTa>.timestamp()                # Seconds since Epoch from DTa.
Format
1
2
3
4
5
6
>>> from datetime import datetime
>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
>>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z")

"Thursday, 14th of May '15, 11:39PM UTC+02:00"
  • For abbreviated weekday and month use '%a' and '%b' .
  • When parsing, '%z' also accepts '±HH:MM' .
Arithmetics
1
2
3
4
<D/DT>   = <D/DT> ±  <TD>
<TD>     = <TD>   ±  <TD>
<TD>     = <TD>   */ <real>
<float>  = <TD>   /  <TD>

` match the start/end of each line.**

  • Argument 'flags=re.DOTALL' makes dot also accept newline.
  • Use r'\1' or '\\1' for backreference.
  • Use '?' to make an operator non-greedy.
Match Object
1
2
3
4
5
<str>   = <Match>.group()   # Whole match. Also group(0).
<str>   = <Match>.group(1)  # Part in first bracket.
<tuple> = <Match>.groups()  # All bracketed parts.
<int>   = <Match>.start()   # Start index of a match.
<int>   = <Match>.end()     # Exclusive end index of a match.
Special Sequences
  • By default digits, whitespaces and alphanumerics from all alphabets are matched, unless 'flags=re.ASCII' argument is used.
  • Use capital letters for negation.
1
2
3
'\d' == '[0-9]'             # Digit
'\s' == '[ \t\n\r\f\v]'     # Whitespace
'\w' == '[a-zA-Z0-9_]'      # Alphanumeric

Format

1
2
<str> = f'{<el_1>}, {<el_2>}'
<str> = '{}, {}'.format(<el_1>, <el_2>)
Attributes
1
2
3
4
5
6
7
8
9
10
11
>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height}'

'187'

>>> '{p.height}'.format(p=person)

'187'
General Options
1
2
3
{<el>:<10}       # '<el>      '
{<el>:^10}       # '   <el>   '
{<el>:>10}       # '      <el>'
1
2
{<el>:.<10}      # '<el>......'
{<el>:>0}        # '<el>'
Strings

** '!r' calls object’s repr() method, instead of str(), to get a string.**

1
2
3
{'abcde'!r:<10}  # "'abcde'   "
{'abcde':.3}     # 'abc'
{'abcde':10.3}   # 'abc       '
Numbers
1
2
3
4
5
6
{ 123456:10,}    # '   123,456'
{ 123456:10_}    # '   123_456'
{ 123456:+10}    # '   +123456'
{-123456:=10}    # '-   123456'
{ 123456: }      # ' 123456'
{-123456: }      # '-123456'
Floats
1
2
3
4
{1.23456:10.3}   # '      1.23'
{1.23456:10.3f}  # '     1.235'
{1.23456:10.3e}  # ' 1.235e+00'
{1.23456:10.3%}  # '  123.456%'
Comparison of float presentation types:
1
2
3
4
5
6
7
8
9
10
11
12
+----------------+----------------+---------------+----------------+-----------------+
|                |    {<float>}   |  {<float>:f}  |   {<float>:e}  |   {<float>:%}   |
+----------------+----------------+---------------+----------------+-----------------+
|    0.000056789 |   '5.6789e-05' |    '0.000057' | '5.678900e-05' |     '0.005679%' |
|    0.00056789  |   '0.00056789' |    '0.000568' | '5.678900e-04' |     '0.056789%' |
|    0.0056789   |   '0.0056789'  |    '0.005679' | '5.678900e-03' |     '0.567890%' |
|    0.056789    |   '0.056789'   |    '0.056789' | '5.678900e-02' |     '5.678900%' |
|    0.56789     |   '0.56789'    |    '0.567890' | '5.678900e-01' |    '56.789000%' |
|    5.6789      |   '5.6789'     |    '5.678900' | '5.678900e+00' |   '567.890000%' |
|   56.789       |  '56.789'      |   '56.789000' | '5.678900e+01' |  '5678.900000%' |
|  567.89        | '567.89'       |  '567.890000' | '5.678900e+02' | '56789.000000%' |
+----------------+----------------+---------------+----------------+-----------------+
1
2
3
4
5
6
7
8
9
10
11
12
+----------------+----------------+---------------+----------------+-----------------+
|                |  {<float>:.2}  | {<float>:.2f} |  {<float>:.2e} |  {<float>:.2%}  |
+----------------+----------------+---------------+----------------+-----------------+
|    0.000056789 |   '5.7e-05'    |      '0.00'   |   '5.68e-05'   |       '0.01%'   |
|    0.00056789  |   '0.00057'    |      '0.00'   |   '5.68e-04'   |       '0.06%'   |
|    0.0056789   |   '0.0057'     |      '0.01'   |   '5.68e-03'   |       '0.57%'   |
|    0.056789    |   '0.057'      |      '0.06'   |   '5.68e-02'   |       '5.68%'   |
|    0.56789     |   '0.57'       |      '0.57'   |   '5.68e-01'   |      '56.79%'   |
|    5.6789      |   '5.7'        |      '5.68'   |   '5.68e+00'   |     '567.89%'   |
|   56.789       |   '5.7e+01'    |     '56.79'   |   '5.68e+01'   |    '5678.90%'   |
|  567.89        |   '5.7e+02'    |    '567.89'   |   '5.68e+02'   |   '56789.00%'   |
+----------------+----------------+---------------+----------------+-----------------+
Ints
1
2
3
{90:c}           # 'Z'
{90:X}           # '5A'
{90:b}           # '1011010'

Numbers

1
2
3
4
<int>      = int(<float/str/bool>)    # Or: math.floor(<float>)
<float>    = float(<int/str/bool>)
<complex>  = complex(real=0, imag=0)  # Or: <real> + <real>j
<Fraction> = fractions.Fraction(numerator=0, denominator=1)
  • ** 'int(<str>)' and 'float(<str>)' raise ‘ValueError’ on malformed strings.**
Basic Functions
1
2
3
4
<num>  = pow(<num>, <num>)            # Or: <num> ** <num>
<real> = abs(<num>)
<int>  = round(<real>)
<real> = round(<real>, ±ndigits)      # `round(126, -1) == 130` 
Math
1
2
3
from math import e, pi, inf, nan
from math import cos, acos, sin, asin, tan, atan, degrees, radians
from math import log, log10, log2
Statistics
1
from statistics import mean, median, variance, pvariance, pstdev
Random
1
2
3
4
5
from random import random, randint, choice, shuffle
<float> = random()
<int>   = randint(from_inclusive, to_inclusive)
<el>    = choice(<list>)
shuffle(<list>)
Bin, Hex
1
2
3
4
<int>     = 0b<bin>            # Or: 0x<hex>
<int>     = int('0b<bin>', 0)  # Or: int('0x<hex>', 0)
<int>     = int('<bin>', 2)    # Or: int('<hex>', 16)
'0b<bin>' = bin(<int>)         # Or: '0x<hex>' = hex(<int>)
Bitwise Operators
1
2
3
4
5
6
<int>     = <int> & <int>      # And
<int>     = <int> | <int>      # Or
<int>     = <int> ^ <int>      # Xor (0 if both bits equal)
<int>     = <int> << n_bits    # Shift left
<int>     = <int> >> n_bits    # Shift right
<int>     = ~<int>             # Compliment (flips bits)
Combinatorics
  • Every function returns an iterator.
  • If you want to print the iterator, you need to pass it to the list() function!
1
from itertools import product, combinations, combinations_with_replacement, permutations
1
2
3
4
5
>>> product([0, 1], repeat=3)

[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
 (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
1
2
3
4
5
>>> product('ab', '12')

[('a', '1'), ('a', '2'),
 ('b', '1'), ('b', '2')]
1
2
3
4
>>> combinations('abc', 2)

[('a', 'b'), ('a', 'c'), ('b', 'c')]
1
2
3
4
5
6
>>> combinations_with_replacement('abc', 2)

[('a', 'a'), ('a', 'b'), ('a', 'c'),
 ('b', 'b'), ('b', 'c'),
 ('c', 'c')]
1
2
3
4
5
6
>>> permutations('abc', 2)

[('a', 'b'), ('a', 'c'),
 ('b', 'a'), ('b', 'c'),
 ('c', 'a'), ('c', 'b')]
Datetime
  • Module ‘datetime’ provides ‘date’ <D> , ‘time’ <T> , ‘datetime’ <DT> and ‘timedelta’ <TD> classes. All are immutable and hashable.
  • Time and datetime can be ‘aware’ <a> , meaning they have defined timezone, or ‘naive’ <n> , meaning they don’t.
  • If object is naive it is presumed to be in system’s timezone.
1
2
from datetime import date, time, datetime, timedelta
from dateutil.tz import UTC, tzlocal, gettz
Constructors
1
2
3
4
5
<D>  = date(year, month, day)
<T>  = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
<DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
<TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
                 minutes=0, hours=0, weeks=0)
  • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
  • ** 'fold=1' means second pass in case of time jumping back for one hour.**
Now
1
2
3
<D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
<DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
<DTa>    = DT.now(<tzinfo>)                 # Aware datetime from current tz time.
  • To extract time use '<DTn>.time()' , '<DTa>.time()' or '<DTa>.timetz()' .
Timezone
1
2
3
<tzinfo> = UTC                              # UTC timezone. London without DST.
<tzinfo> = tzlocal()                        # Local timezone. Also gettz().
<tzinfo> = gettz('<Cont.>/<City>')          # Timezone from 'Continent/City_Name' str.
1
2
<DTa>    = <DT>.astimezone(<tzinfo>)        # Datetime, converted to passed timezone.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>)  # Unconverted object with new timezone.
Encode
1
2
3
4
5
<D/T/DT> = D/T/DT.fromisoformat('<iso>')    # Object from ISO string.
<DT>     = DT.strptime(<str>, '<format>')   # Datetime from str, according to format.
<D/DTn>  = D/DT.fromordinal(<int>)          # D/DTn from days since Christ, at midnight.
<DTn>    = DT.fromtimestamp(<real>)         # Local time DTn from seconds since Epoch.
<DTa>    = DT.fromtimestamp(<real>, <tz.>)  # Aware datetime from seconds since Epoch.
  • ISO strings come in following forms: 'YYYY-MM-DD' , 'HH:MM:SS.ffffff[±<offset>]' , or both separated by 'T' . Offset is formatted as: 'HH:MM' .
  • On Unix systems Epoch is '1970-01-01 00:00 UTC' , '1970-01-01 01:00 CET' , …
Decode
1
2
3
4
5
<str>    = <D/T/DT>.isoformat()             # ISO string representation.
<str>    = <D/T/DT>.strftime('<format>')    # Custom string representation.
<int>    = <D/DT>.toordinal()               # Days since Christ, ignoring time and tz.
<float>  = <DTn>.timestamp()                # Seconds since Epoch from DTn in local time.
<float>  = <DTa>.timestamp()                # Seconds since Epoch from DTa.
Format
1
2
3
4
5
6
>>> from datetime import datetime
>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
>>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z")

"Thursday, 14th of May '15, 11:39PM UTC+02:00"
  • For abbreviated weekday and month use '%a' and '%b' .
  • When parsing, '%z' also accepts '±HH:MM' .
Arithmetics
1
2
3
4
<D/DT>   = <D/DT> ±  <TD>
<TD>     = <TD>   ±  <TD>
<TD>     = <TD>   */ <real>
<float>  = <TD>   /  <TD>

comments powered by Disqus