minte9
LearnRemember



Time

Epoch timestamps can be used to profile code.
 
"""Time
Calculate the time of a code to run.
Code example: product of the first 100.000 numbers.
"""
import time

def product():
    p = 1
    for i in range(1, 100000):
        p = p * i
    return p

start = time.time()
prod = product()
end = time.time()

print('The result is %s digits long.' % len(str(prod)))
print('Took %s seconds to calculate.' % (end - start))
    # The result is 456569 digits long.
    # Took 3.54418683052063 seconds to calculate.

Sleep

Use sleep() if you want to pause the program for a while.
 
"""Time sleep
Number of seconds you want the program to stay paused.
Ctrl-C to stop the program raise an exception.
"""
import time, sys

def tick_tack():
    print('Tick'), time.sleep(1)
    print('Tock'), time.sleep(1)

while(True):
    try:
        tick_tack()
    except KeyboardInterrupt:
        sys.exit()

    # Tick
    # Tock
    # Tick
    # Tock
    # Tick
    # Tock

Datetime

To display a date in an useful format, use datetime module.
 
"""Datetime
Display today date (year, month, day, etc)
The datetime has its own datatime data type.
"""
import datetime

# now
now = datetime.datetime.now()
print(now) 
    # 2021-12-09 18:56:45.224853

# date
dt = datetime.datetime(2019, 10, 21, 16, 29, 0)
assert dt.month == 10
assert dt.day == 21
assert dt.second == 0

Delta

Datetime also provides a timedelta data type.
 
"""Time delta
Datetime module provides a timedelta data type (duration).
Python knows how many days are in each month, also the leap years.
"""
import datetime, time, sys

"""Future day"""
now = datetime.datetime.now()
future = now + datetime.timedelta(days=1000)
print(now) 
    # 2021-12-09 19:09:26.542590
print(future.year) 
    # 2024

"""You can pause a program until a specific date."""
now = datetime.datetime.now()
tommorrow = now + datetime.timedelta(days=1)
while datetime.datetime.now() < tommorrow:
    try:
        time.sleep(1)
    except KeyboardInterrupt: # Ctrl-C
        sys.exit()



  Last update: 420 days ago