11.7. Datetime Timestamp¶
11.7.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 (1901-12-13 20:45:52 UTC)
If you add 1 to max value, you will get overflow to min value
Linux kernel 5.6 (released 29 March 2020) has a fix for this problem so that 32-bit systems can run beyond the year 2038
https://lore.kernel.org/lkml/CAHk-=wi9ZT7Stg-uSpX0UWQzam6OP9Jzz6Xu1CkYu1cicpD5OA@mail.gmail.com/
11.7.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()
11.7.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)
11.7.4. Assignments¶
"""
* 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 = ...