Basic Python

datetime, timedelta, strftime, sleep, random.randint, zfill, format

Naranjito 2021. 5. 17. 16:14
  • datetime

The module works with dates and time.

x=datetime.datetime.now()
x
>>>
datetime.datetime(2021, 5, 14, 13, 7, 18, 347271)

 

  • timedelta

It presents under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations.

from datetime import datetime, timedelta
for day in range(5,0,-1):
    delta=timedelta(days=day)
    print(x-delta)
>>>
2021-05-09 14:24:48.451735
2021-05-10 14:24:48.451735
2021-05-11 14:24:48.451735
2021-05-12 14:24:48.451735
2021-05-13 14:24:48.451735

 

  • strftime

String From Time, can format the time in different desirable ways.

time=x.strftime('%H:%M:%S')
print(time)
>>>
14:24:48

 

  • sleep

It suspends(waits) execution of the currunt thread for a given number of seconds. 

import time, datetime

while 1:
    x=datetime.datetime.now()
    print(x)
    time.sleep(1.0)
>>>
2021-05-14 15:04:35.756793
2021-05-14 15:04:36.760662
2021-05-14 15:04:37.765853
2021-05-14 15:04:38.768300
...

 

  • random.randint(start,stop)

Random Integer, returns a number between start and stop(both included).

import random 
num1 = random.randint(0, 999)
print(num1)
>>>
151

 

  • zfill()

Zero Fill, fill the string with zeros until it is ()characters long.

a = "hello"
b = "welcome to the jungle"
c = "10.000"

print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
>>>
00000hello
welcome to the jungle
000010.000

 

  • format

Call str.format(float) with str to convert float to a string representation of an amount of mony.

num = 10000000
print(f"{num:,}")
>>>
10,000,000

num = 10000000
print(f"{num:,.2f}")
>>>
10,000,000.00