2.4. Datetime Timestamp

2.4.1. What is timestamp?

  • Seconds since midnight of January 1st, 1970 (1970-01-01 00:00:00 UTC)

  • Unix era, also known as "epoch"

  • In most systems represented as 32-bit integer

  • Max value is 2,147,483,647 (2038-01-19 03:14:07 UTC)

  • Min value is -2,147,483,647 (1902-12-13 20:45:53 UTC)

  • If you add 1 to max value, you will get overflow to min value

2.4.2. Get current timestamp

Get current timestamp using datetime module:

from datetime import datetime

datetime.now().timestamp()
# 1567298992.679585

Get current timestamp using time module:

import time

time.time()
# 1567298992.679617

2.4.3. Convert timestamp to datetime

Convert timestamp to datetime:

from datetime import datetime

datetime.fromtimestamp(267809220)
# datetime.datetime(1978, 6, 27, 15, 27)
  • JavaScript has timestamp in milliseconds

  • To convert from milliseconds we have to divide by 1000

Convert JavaScript timestamp to datetime:

from datetime import datetime

MILLISECONDS = 1000

datetime.fromtimestamp(267809220000 / MILLISECONDS)
# datetime.datetime(1978, 6, 27, 17, 27)

2.4.4. Assignments

Code 2.38. Solution
"""
* Assignment: Datetime Timestamp Limits
* Complexity: easy
* Lines of code: 1 lines
* Time: 5 min

English:
    1. Use data from "Given" section (see below)
    2. Convert given dates to `datetime` objects
    3. Print timestamp for each date
    4. What is special about those dates?

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Przekonwertuj podane daty do obiektów `datetime`
    3. Wypisz timestamp każdej daty
    4. Co to za daty?

    >>> assert type(a) is float, \
    '`a` must be a float object'

    >>> assert type(b) is float, \
    '`b` must be a float object'

    >>> assert type(c) is float, \
    '`c` must be a float object'

    >>> a
    -2115947647.0
    >>> b
    0.0
    >>> c
    2147483647.0
"""


# Given
from datetime import datetime


A = '1902-12-13T20:45:53+00:00'
B = '1970-01-01T00:00:00+00:00'
C = '2038-01-19T03:14:07+00:00'

a = ...  # float: timestamp of A
b = ...  # float: timestamp of B
c = ...  # float: timestamp of C