8.8. Datetime Timestamp

8.8.1. What is timestamp?

8.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()

8.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)

8.8.4. Assignments

# %% About
# - Name: Datetime Timestamp Limits
# - Difficulty: easy
# - Lines: 1
# - Minutes: 5

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% 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ść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

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

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

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

>>> result_a
-2115947647.0

>>> result_b
0.0

>>> result_c
2147483647.0
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports
from datetime import datetime

# %% Types
result_a: float
result_b: float
result_c: float

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

# %% Result
result_a = ...
result_b = ...
result_c = ...