5.8. Datetime Timestamp

5.8.1. What is timestamp?

5.8.2. Get current timestamp

Get current timestamp using datetime module:

>>> from datetime import datetime
>>>
>>>
>>> current_timestamp = datetime.now().timestamp()

Get current timestamp using time module:

>>> import time
>>>
>>>
>>> current_timestamp = time.time()

5.8.3. Convert timestamp to datetime

Convert timestamp to datetime:

>>> from datetime import datetime
>>>
>>>
>>> datetime.fromtimestamp(267809220)  
datetime.datetime(1978, 6, 27, 17, 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)

5.8.4. Assignments

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

English:
    1. Convert given dates to `datetime` objects
    2. Print timestamp for each date
    3. What is special about those dates?
    4. Run doctests - all must succeed

Polish:
    1. Przekonwertuj podane daty do obiektów `datetime`
    2. Wypisz timestamp każdej daty
    3. Co to za daty?
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> 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
"""

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'

# timestamp of A
# type: float
a = ...

# timestamp of B
# type: float
b = ...

# timestamp of C
# type: float
c = ...