5/09/2020

Python - Generate Random Numbers and Data Using the random Module

** Generate Random Numbers and Data Using the random Module


==========================================

import random

value = random.random()

print(value)


---------------------------------

0.9763078125267174

---------------------------------

0.7991571271641462

---------------------------------

0.05848808751761392

---------------------------------
...

---------------------------------

==========================================

import random

value = random.uniform(1, 10)

print(value)

---------------------------------

7.158342523317879

1.0916879633147998

7.9148940717269705

...

---------------------------------

==========================================

import random

value = random.randint(1, 6)

print(value)

---------------------------------

3

3

5

5

5

2

...

---------------------------------

==========================================


import random

value = random.randint(0, 1)

print(value)

---------------------------------

0

0

1

1

0

1

...

---------------------------------

==========================================

import random

greetings = ['Hello', 'Hi', 'Hey', 'Howdy', 'Hola']

value = random.choice(greetings)

print(value + ', LinuxerHAN!')


---------------------------------

Hey, LinuxerHAN!


Hola, LinuxerHAN!


Hello, LinuxerHAN!


...

---------------------------------

==========================================

import random

colors = ['Red', 'Black', 'Green']

results = random.choices(colors, k = 10)

print(results)

---------------------------------

['Green', 'Green', 'Red', 'Red', 'Black', 'Black', 'Black', 'Red', 'Green', 'Black']

---------------------------------

==========================================

import random

colors = ['Red', 'Black', 'Green']

results = random.choices(colors, weights=[18, 18, 2], k = 10)

print(results)

---------------------------------

['Green', 'Black', 'Black', 'Black', 'Red', 'Red', 'Black', 'Red', 'Black', 'Black']

['Black', 'Red', 'Red', 'Black', 'Black', 'Black', 'Black', 'Black', 'Red', 'Red']

['Black', 'Red', 'Black', 'Red', 'Red', 'Red', 'Black', 'Red', 'Black', 'Red']

...

---------------------------------

==========================================

import random

deck = list(range(1,53))

print(deck)

---------------------------------

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]

---------------------------------

==========================================

import random

deck = list(range(1,53))

random.shuffle(deck)

print(deck)

---------------------------------

[19, 47, 4, 46, 22, 9, 2, 14, 8, 51, 39, 13, 36, 31, 40, 11, 45, 48, 16, 26, 43, 37, 15, 42, 52, 29, 10, 1, 24, 35, 32, 30, 38, 12, 41, 20, 18, 23, 17, 25, 28, 49, 34, 3, 5, 44, 50, 27, 33, 21, 6, 7]

---------------------------------

==========================================

import random

deck = list(range(1,53))

hand = random.sample(deck, k = 5)

print(hand)

---------------------------------

[8, 31, 28, 40, 35]

[41, 28, 40, 11, 4]

[13, 48, 44, 7, 15]

...

---------------------------------

==========================================

import random

first_names = ['김', '이', '박', '최', '한', '전', '양', '손', '신', '황']

last_names = ['영진', '미숙', '재인', '용석', '미자', '수연', '정수', '선미', '미현', '성규']

street_names = ['동성로', '홍대', '보문로', '명동', '자갈치', '한옥', '북한로', '펀치볼', '역전', '북문로']

fake_cities = ['메트로폴리스', '에리어', '킹스 랜딩', '써니달', '베드락', '사우스 팍', '아틀란티스']

states = ['서울', '경기도', '인천', '대구', '경상도', '전라도', '강원도', '울산', '부산', '충청도', '광주', '세종', '제주도']

for num in range(10):
first = random.choice(first_names)
last = random.choice(last_names)

phone = f'{random.randint(100, 999)}-5555-{random.randint(1000, 9999)}'

street_num = random.randint(100, 999)
street = random.choice(street_names)
city = random.choice(fake_cities)
state = random.choice(states)
zip_code = random.randint(10000, 99999)
address = f'{street_num} {street} St., {city} {state} {zip_code}'

email = first.lower() + last.lower() + '@linuxerhan.com'

print(f'{first} {last}\n{phone}\n{address}\n{email}\n')

---------------------------------

이 미숙
335-5555-3413
624 북문로 St., 베드락 대구 63399
이미숙@linuxerhan.com

신 영진
796-5555-9023
113 한옥 St., 베드락 전라도 92185
신영진@linuxerhan.com

최 미현
118-5555-7156
117 북문로 St., 써니달 대구 72062
최미현@linuxerhan.com

전 미자
364-5555-1847
161 북문로 St., 사우스 팍 강원도 33914
전미자@linuxerhan.com

김 미자
890-5555-7513
179 명동 St., 써니달 세종 84435
김미자@linuxerhan.com

황 선미
339-5555-2032
428 펀치볼 St., 킹스 랜딩 세종 69956
황선미@linuxerhan.com

전 수연
386-5555-1678
297 동성로 St., 써니달 강원도 84873
전수연@linuxerhan.com

최 수연
939-5555-7510
702 북한로 St., 킹스 랜딩 경상도 84370
최수연@linuxerhan.com

김 영진
528-5555-6917
676 홍대 St., 사우스 팍 서울 71470
김영진@linuxerhan.com

전 용석
854-5555-4103
296 명동 St., 베드락 대구 67091
전용석@linuxerhan.com


---------------------------------


Python - Automate Parsing and Renaming of Multiple Files

** Automate Parsing and Renaming of Multiple Files


==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

print(os.getcwd())

---------------------------------

C:\Users\purunet\Documents\py1\mt

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
print(f)

---------------------------------

멋진인생 - mt - #8.mp3
백세인생 - mt - #3 .mp3
뿐이고 - mt - #9.mp3
십분내로 - mt - #7.mp3
어느 60대 노부부이야기 - mt - #1.mp3
어쩌다 마주친 그대 - mt - #12.mp3
여자의 일생 - mt - #10.mp3
창밖의 여자 - mt - #11.mp3
천상재회 - mt - #5.mp3
청춘 - mt - #4.mp3
한오백년 - mt - #6.mp3
희망가 - mt - #2.mp3

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
print(os.path.splitext(f))


---------------------------------

('멋진인생 - mt - #8', '.mp3')
('백세인생 - mt - #3 ', '.mp3')
('뿐이고 - mt - #9', '.mp3')
('십분내로 - mt - #7', '.mp3')
('어느 60대 노부부이야기 - mt - #1', '.mp3')
('어쩌다 마주친 그대 - mt - #12', '.mp3')
('여자의 일생 - mt - #10', '.mp3')
('창밖의 여자 - mt - #11', '.mp3')
('천상재회 - mt - #5', '.mp3')
('청춘 - mt - #4', '.mp3')
('한오백년 - mt - #6', '.mp3')
('희망가 - mt - #2', '.mp3')

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name)

---------------------------------

멋진인생 - mt - #8
백세인생 - mt - #3
뿐이고 - mt - #9
십분내로 - mt - #7
어느 60대 노부부이야기 - mt - #1
어쩌다 마주친 그대 - mt - #12
여자의 일생 - mt - #10
창밖의 여자 - mt - #11
천상재회 - mt - #5
청춘 - mt - #4
한오백년 - mt - #6
희망가 - mt - #2

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name.split('-'))


---------------------------------

['멋진인생 ', ' mt ', ' #8']
['백세인생 ', ' mt ', ' #3 ']
['뿐이고 ', ' mt ', ' #9']
['십분내로 ', ' mt ', ' #7']
['어느 60대 노부부이야기 ', ' mt ', ' #1']
['어쩌다 마주친 그대 ', ' mt ', ' #12']
['여자의 일생 ', ' mt ', ' #10']
['창밖의 여자 ', ' mt ', ' #11']
['천상재회 ', ' mt ', ' #5']
['청춘 ', ' mt ', ' #4']
['한오백년 ', ' mt ', ' #6']
['희망가 ', ' mt ', ' #2']

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)

f_title, f_course, f_num = file_name.split('-')

print(f_title)


---------------------------------

멋진인생
백세인생
뿐이고
십분내로
어느 60대 노부부이야기
어쩌다 마주친 그대
여자의 일생
창밖의 여자
천상재회
청춘
한오백년
희망가

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)

f_title, f_course, f_num = file_name.split('-')

print(f_course)

---------------------------------

 mt
 mt
 mt
 mt
 mt
 mt
 mt
 mt
 mt
 mt
 mt
 mt

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)

f_title, f_course, f_num = file_name.split('-')

print(f_num)

---------------------------------

 #8
 #3
 #9
 #7
 #1
 #12
 #10
 #11
 #5
 #4
 #6
 #2

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
f_name, f_ext = os.path.splitext(f)

f_title, f_course, f_num = f_name.split('-')

print('{}-{}-{}{}'.format(f_num, f_course, f_title, f_ext))


---------------------------------

 #8- mt -멋진인생 .mp3
 #3 - mt -백세인생 .mp3
 #9- mt -뿐이고 .mp3
 #7- mt -십분내로 .mp3
 #1- mt -어느 60대 노부부이야기 .mp3
 #12- mt -어쩌다 마주친 그대 .mp3
 #10- mt -여자의 일생 .mp3
 #11- mt -창밖의 여자 .mp3
 #5- mt -천상재회 .mp3
 #4- mt -청춘 .mp3
 #6- mt -한오백년 .mp3
 #2- mt -희망가 .mp3

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
f_name, f_ext = os.path.splitext(f)

f_title, f_course, f_num = f_name.split('-')

f_title = f_title.strip()
f_course = f_course.strip()
f_num = f_num.strip()


print('{}-{}-{}{}'.format(f_num, f_course, f_title, f_ext))

---------------------------------

#8-mt-멋진인생.mp3
#3-mt-백세인생.mp3
#9-mt-뿐이고.mp3
#7-mt-십분내로.mp3
#1-mt-어느 60대 노부부이야기.mp3
#12-mt-어쩌다 마주친 그대.mp3
#10-mt-여자의 일생.mp3
#11-mt-창밖의 여자.mp3
#5-mt-천상재회.mp3
#4-mt-청춘.mp3
#6-mt-한오백년.mp3
#2-mt-희망가.mp3

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
f_name, f_ext = os.path.splitext(f)

f_title, f_course, f_num = f_name.split('-')

f_title = f_title.strip()
f_course = f_course.strip()
f_num = f_num.strip()[1:]


print('{}-{}-{}{}'.format(f_num, f_course, f_title, f_ext))

---------------------------------

8-mt-멋진인생.mp3
3-mt-백세인생.mp3
9-mt-뿐이고.mp3
7-mt-십분내로.mp3
1-mt-어느 60대 노부부이야기.mp3
12-mt-어쩌다 마주친 그대.mp3
10-mt-여자의 일생.mp3
11-mt-창밖의 여자.mp3
5-mt-천상재회.mp3
4-mt-청춘.mp3
6-mt-한오백년.mp3
2-mt-희망가.mp3

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
f_name, f_ext = os.path.splitext(f)

f_title, f_course, f_num = f_name.split('-')

f_title = f_title.strip()
f_course = f_course.strip()
f_num = f_num.strip()[1:].zfill(2)


print('{}-{}-{}{}'.format(f_num, f_course, f_title, f_ext))


---------------------------------

08-mt-멋진인생.mp3
03-mt-백세인생.mp3
09-mt-뿐이고.mp3
07-mt-십분내로.mp3
01-mt-어느 60대 노부부이야기.mp3
12-mt-어쩌다 마주친 그대.mp3
10-mt-여자의 일생.mp3
11-mt-창밖의 여자.mp3
05-mt-천상재회.mp3
04-mt-청춘.mp3
06-mt-한오백년.mp3
02-mt-희망가.mp3

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1\\mt')

for f in os.listdir():
f_name, f_ext = os.path.splitext(f)

f_title, f_course, f_num = f_name.split('-')

f_title = f_title.strip()
f_course = f_course.strip()
f_num = f_num.strip()[1:].zfill(2)


print('{}-{}{}'.format(f_num, f_title, f_ext))


---------------------------------

08-멋진인생.mp3
03-백세인생.mp3
09-뿐이고.mp3
07-십분내로.mp3
01-어느 60대 노부부이야기.mp3
12-어쩌다 마주친 그대.mp3
10-여자의 일생.mp3
11-창밖의 여자.mp3
05-천상재회.mp3
04-청춘.mp3
06-한오백년.mp3
02-희망가.mp3

---------------------------------









5/08/2020

Python - File Objects - Reading and Writing to Files

** File Objects - Reading and Writing to Files


==========================================

# File Objects

f = open('test.txt', 'r')

print(f.name)

f.close()

---------------------------------

test.txt

---------------------------------

==========================================

f = open('test.txt', 'r')

print(f.mode)

f.close()

---------------------------------

r

---------------------------------

==========================================

with open('test.txt', 'r') as f:
pass

print(f.closed)

---------------------------------

True

---------------------------------

==========================================

with open('test.txt', 'r') as f:
pass

print(f.read())

---------------------------------

 print(f.read())
ValueError: I/O operation on closed file.


---------------------------------

==========================================

with open('test.txt', 'r') as f:
f_contets = f.read()
print(f_contets)



---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

---------------------------------

==========================================

with open('test.txt', 'r') as f:
f_contets = f.readlines()
print(f_contets)


---------------------------------

['1) This is a test file!\n', '2) With multiple lines of data...\n', '3) Third line\n', '4) Fourth line\n', '5) Fifth line\n', '6) Sixth line\n', '7) Seventh line\n', '8) Eighth line\n', '9) Ninth line\n', '10) Tenth line']

---------------------------------

==========================================

with open('test.txt', 'r') as f:
f_contets = f.readline()
print(f_contets)

---------------------------------

1) This is a test file!

---------------------------------

==========================================

with open('test.txt', 'r') as f:
f_contets = f.readline()
print(f_contets)

f_contets = f.readline()
print(f_contets)


---------------------------------

1) This is a test file!

2) With multiple lines of data...

---------------------------------

==========================================

with open('test.txt', 'r') as f:
f_contets = f.readline()
print(f_contets, end = '')

f_contets = f.readline()
print(f_contets, end = '')


---------------------------------

1) This is a test file!
2) With multiple lines of data...

---------------------------------

==========================================

with open('test.txt', 'r') as f:

for line in f:
print(line, end = '')

---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

---------------------------------

==========================================

with open('test.txt', 'r') as f:

f_contents = f.read()
print(f_contents, end = '')

---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

---------------------------------


==========================================

with open('test.txt', 'r') as f:

f_contents = f.read(100)
print(f_contents, end = '')

---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line

---------------------------------

==========================================

with open('test.txt', 'r') as f:

f_contents = f.read(100)
print(f_contents, end = '')


f_contents = f.read(100)
print(f_contents, end = '')


---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

---------------------------------

==========================================

with open('test.txt', 'r') as f:

f_contents = f.read(100)
print(f_contents, end = '')


f_contents = f.read(100)
print(f_contents, end = '')

f_contents = f.read(100)
print(f_contents, end = '')

---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

---------------------------------

==========================================

with open('test.txt', 'r') as f:

size_to_read = 100

f_contents = f.read(size_to_read)

while len(f_contents) > 0:
print(f_contents, end = '')
f_contents = f.read(size_to_read)

---------------------------------

1) This is a test file!
2) With multiple lines of data...
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

---------------------------------

==========================================

with open('test.txt', 'r') as f:

size_to_read = 10

f_contents = f.read(size_to_read)

while len(f_contents) > 0:
print(f_contents, end = '*')
f_contents = f.read(size_to_read)

---------------------------------

1) This is* a test fi*le!
2) Wit*h multiple* lines of *data...
3)* Third lin*e
4) Fourt*h line
5) *Fifth line*
6) Sixth *line
7) Se*venth line*
8) Eighth* line
9) N*inth line
*10) Tenth *line
*

==========================================

with open('test.txt', 'r') as f:

size_to_read = 10

f_contents = f.read(size_to_read)

print(f.tell())


---------------------------------

10

---------------------------------

==========================================

with open('test.txt', 'r') as f:

size_to_read = 10

f_contents = f.read(size_to_read)
print(f_contents, end = '')

f_contents = f.read(size_to_read)
print(f_contents, end = '')

print('\n')
print('-'*80)

print(f.tell())

---------------------------------

1) This is a test fi

--------------------------------------------------------------------------------
20

---------------------------------

==========================================

with open('test.txt', 'r') as f:

size_to_read = 10

f_contents = f.read(size_to_read)
print(f_contents, end = '')

f_contents = f.read(size_to_read)
print(f_contents)

---------------------------------

1) This is a test fi

---------------------------------

==========================================

with open('test.txt', 'r') as f:

size_to_read = 10

f_contents = f.read(size_to_read)
print(f_contents, end = '')

f.seek(0)

f_contents = f.read(size_to_read)
print(f_contents)

---------------------------------

1) This is1) This is

---------------------------------

==========================================

with open('test.txt', 'r') as f:
f.write('Test')

---------------------------------

 f.write('Test')
io.UnsupportedOperation: not writable

---------------------------------

==========================================

with open('test2.txt', 'w') as f:
f.write('Test')

---------------------------------




---------------------------------

==========================================

with open('test2.txt', 'w') as f:
f.write('Test')
f.write('Test')

---------------------------------




---------------------------------

==========================================

with open('test2.txt', 'w') as f:
f.write('Test')
f.seek(0)
f.write('Test')

---------------------------------




---------------------------------

==========================================

with open('test2.txt', 'w') as f:
f.write('Test')
f.seek(0)
f.write('R')

---------------------------------



---------------------------------

==========================================

with open('test.txt', 'r') as rf:
with open('test_copy.txt', 'w') as wf:
for line in rf:
wf.write(line)

---------------------------------




---------------------------------

==========================================

ith open('1.jpg', 'r') as rf:
with open('1_copy.jpg', 'w') as wf:
for line in rf:
wf.write(line)

---------------------------------

  for line in rf:
UnicodeDecodeError: 'cp949' codec can't decode byte 0xff in position 0: illegal multibyte sequence

---------------------------------

==========================================

with open('1.jpg', 'rb') as rf:
with open('1_copy.jpg', 'wb') as wf:
for line in rf:
wf.write(line)

---------------------------------




==========================================

with open('1.jpg', 'rb') as rf:
with open('1_copy.jpg', 'wb') as wf:
chunk_size = 4096
rf_chunk = rf.read(chunk_size)
while len(rf_chunk) > 0:
wf.write(rf_chunk)
rf_chunk = rf.read(chunk_size)

---------------------------------





5/07/2020

Python - Datetime Module

** Datetime Module


==========================================

import datetime

d = datetime.date(2020, 5, 7)

print(d)

---------------------------------

2020-05-07

---------------------------------

==========================================

import datetime

d = datetime.date(2020, 05, 7)

print(d)

---------------------------------

    d = datetime.date(2020, 05, 7)
                             ^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

---------------------------------

==========================================

import datetime

tday = datetime.date.today()

print(tday)
print(tday.year)
print(tday.day)

# Monday 0, Sunday 6
print(tday.weekday())

# Monday 1, Sunday 7
print(tday.isoweekday())

---------------------------------

2020-05-07
2020
7
3
4

---------------------------------

==========================================

import datetime

tday = datetime.date.today()

tdelta = datetime.timedelta(days = 7)

print(tday + tdelta)

print(tday - tdelta)


---------------------------------

2020-05-14
2020-04-30

---------------------------------

==========================================

import datetime

tday = datetime.date.today()

bday = datetime.date(2020, 4, 9)

till_bday = bday - tday

print(till_bday.days)

print(till_bday.total_seconds())

---------------------------------

-28
-2419200.0

---------------------------------

==========================================

import datetime

t = datetime.time(9, 30, 45, 10000)

print(t)

print(t.hour)

---------------------------------

09:30:45.010000
9

---------------------------------

==========================================

import datetime

dt = datetime.datetime(2020, 5, 7, 12, 30, 45, 100000)

print(dt)

print(dt.date())

print(dt.time())

print(dt.year)

---------------------------------

2020-05-07 12:30:45.100000
2020-05-07
12:30:45.100000
2020

---------------------------------

==========================================

import datetime

dt = datetime.datetime(2020, 5, 7, 12, 30, 45, 100000)

tdelta = datetime.timedelta(days = 7)

print(dt + tdelta)

---------------------------------

2020-05-14 12:30:45.100000

---------------------------------

==========================================

import datetime

dt = datetime.datetime(2020, 5, 7, 12, 30, 45, 100000)

tdelta = datetime.timedelta(hours = 12)

print(dt + tdelta)


---------------------------------

2020-05-08 00:30:45.100000

---------------------------------

==========================================

import datetime

dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()


print(dt_today)
print(dt_now)
print(dt_utcnow)

---------------------------------

2020-05-07 13:51:01.896773
2020-05-07 13:51:01.896773
2020-05-07 04:51:01.896773

---------------------------------

==========================================

### pip install pytz

==========================================

### python -m pip install --upgrade pip

WARNING: You are using pip version 19.2.3, however version 20.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

==========================================

==========================================

import datetime
import pytz


dt = datetime.datetime(2020, 5, 7, 12, 30, 45, tzinfo=pytz.UTC)
print(dt)

dt_now = datetime.datetime.now(tz = pytz.UTC)
print(dt_now)

dt_utcnow = datetime.datetime.utcnow().replace(tzinfo = pytz. UTC)
print(dt_utcnow)


---------------------------------

2020-05-07 12:30:45+00:00
2020-05-07 05:15:28.549767+00:00
2020-05-07 05:15:28.549767+00:00

---------------------------------

==========================================

import datetime
import pytz


dt_utcnow = datetime.datetime.now(tz = pytz.UTC)
print(dt_utcnow)

dt_mtn = dt_utcnow.astimezone(pytz.timezone('US/Mountain'))
print(dt_mtn)

---------------------------------

2020-05-07 05:18:08.789939+00:00
2020-05-06 23:18:08.789939-06:00

---------------------------------

==========================================

import datetime
import pytz

dt_utcnow = datetime.datetime.now(tz = pytz.UTC)
print(dt_utcnow)

dt_mtn = datetime.datetime.now()
print(dt_mtn)

---------------------------------

2020-05-07 05:22:35.481211+00:00
2020-05-07 14:22:35.481211

---------------------------------

==========================================

import datetime
import pytz

dt_utcnow = datetime.datetime.now(tz = pytz.UTC)
print(dt_utcnow)

dt_mtn = datetime.datetime.now()
dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))


print(dt_mtn)

---------------------------------

2020-05-07 05:24:16.274983+00:00
2020-05-07 14:24:16.274983

---------------------------------

==========================================

import datetime
import pytz

dt_utcnow = datetime.datetime.now(tz = pytz.UTC)

dt_mtn = datetime.datetime.now()
mtn_tz = pytz.timezone('US/Mountain')

dt_mtn = mtn_tz.localize(dt_mtn)

print(dt_mtn)

---------------------------------

2020-05-07 14:26:36.859033-06:00

---------------------------------

==========================================

import datetime
import pytz

dt_utcnow = datetime.datetime.now(tz = pytz.UTC)

dt_mtn = datetime.datetime.now()
mtn_tz = pytz.timezone('US/Mountain')

dt_mtn = mtn_tz.localize(dt_mtn)

dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))

print(dt_east)

---------------------------------

2020-05-07 16:27:49.736207-04:00

---------------------------------

==========================================

import datetime
import pytz

dt_mtn = datetime.datetime.now(tz = pytz.timezone('US/Mountain'))

print(dt_mtn.isoformat())

print(dt_mtn.strftime('%B %d, %Y'))

dt_str = 'May 06, 2020'

dt = datetime.datetime.strptime(dt_str, '%B %d, %Y')
print(dt)


# strftime - Datetime to String
# strptime - String to Datetime

---------------------------------

2020-05-06T23:33:25.981466-06:00
May 06, 2020
2020-05-06 00:00:00

---------------------------------

==========================================

import datetime
import pytz

for tz in pytz.all_timezones:
print(tz)

---------------------------------

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
Africa/Brazzaville
Africa/Bujumbura
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/Conakry
Africa/Dakar
Africa/Dar_es_Salaam
Africa/Djibouti
Africa/Douala
Africa/El_Aaiun
Africa/Freetown
Africa/Gaborone
Africa/Harare
Africa/Johannesburg
Africa/Juba
Africa/Kampala
Africa/Khartoum
Africa/Kigali
Africa/Kinshasa
Africa/Lagos
Africa/Libreville
Africa/Lome
Africa/Luanda
Africa/Lubumbashi
Africa/Lusaka
Africa/Malabo
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Mogadishu
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Niamey
Africa/Nouakchott
Africa/Ouagadougou
Africa/Porto-Novo
Africa/Sao_Tome
Africa/Timbuktu
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Anguilla
America/Antigua
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/ComodRivadavia
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Aruba
America/Asuncion
America/Atikokan
America/Atka
America/Bahia
America/Bahia_Banderas
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Buenos_Aires
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Catamarca
America/Cayenne
America/Cayman
America/Chicago
America/Chihuahua
America/Coral_Harbour
America/Cordoba
America/Costa_Rica
America/Creston
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Dominica
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Ensenada
America/Fort_Nelson
America/Fort_Wayne
America/Fortaleza
America/Glace_Bay
America/Godthab
America/Goose_Bay
America/Grand_Turk
America/Grenada
America/Guadeloupe
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Indianapolis
America/Inuvik
America/Iqaluit
America/Jamaica
America/Jujuy
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Knox_IN
America/Kralendijk
America/La_Paz
America/Lima
America/Los_Angeles
America/Louisville
America/Lower_Princes
America/Maceio
America/Managua
America/Manaus
America/Marigot
America/Martinique
America/Matamoros
America/Mazatlan
America/Mendoza
America/Menominee
America/Merida
America/Metlakatla
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Montreal
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Nuuk
America/Ojinaga
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Acre
America/Porto_Velho
America/Puerto_Rico
America/Punta_Arenas
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Rosario
America/Santa_Isabel
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Shiprock
America/Sitka
America/St_Barthelemy
America/St_Johns
America/St_Kitts
America/St_Lucia
America/St_Thomas
America/St_Vincent
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Tortola
America/Vancouver
America/Virgin
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Macquarie
Antarctica/Mawson
Antarctica/McMurdo
Antarctica/Palmer
Antarctica/Rothera
Antarctica/South_Pole
Antarctica/Syowa
Antarctica/Troll
Antarctica/Vostok
Arctic/Longyearbyen
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Ashkhabad
Asia/Atyrau
Asia/Baghdad
Asia/Bahrain
Asia/Baku
Asia/Bangkok
Asia/Barnaul
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Calcutta
Asia/Chita
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Colombo
Asia/Dacca
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Famagusta
Asia/Gaza
Asia/Harbin
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Istanbul
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kashgar
Asia/Kathmandu
Asia/Katmandu
Asia/Khandyga
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macao
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novokuznetsk
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qostanay
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Saigon
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Srednekolymsk
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Tel_Aviv
Asia/Thimbu
Asia/Thimphu
Asia/Tokyo
Asia/Tomsk
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Asia/Ust-Nera
Asia/Vientiane
Asia/Vladivostok
Asia/Yakutsk
Asia/Yangon
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faeroe
Atlantic/Faroe
Atlantic/Jan_Mayen
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/St_Helena
Atlantic/Stanley
Australia/ACT
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Canberra
Australia/Currie
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/LHI
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/NSW
Australia/North
Australia/Perth
Australia/Queensland
Australia/South
Australia/Sydney
Australia/Tasmania
Australia/Victoria
Australia/West
Australia/Yancowinna
Brazil/Acre
Brazil/DeNoronha
Brazil/East
Brazil/West
CET
CST6CDT
Canada/Atlantic
Canada/Central
Canada/Eastern
Canada/Mountain
Canada/Newfoundland
Canada/Pacific
Canada/Saskatchewan
Canada/Yukon
Chile/Continental
Chile/EasterIsland
Cuba
EET
EST
EST5EDT
Egypt
Eire
Etc/GMT
Etc/GMT+0
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-0
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9
Etc/GMT0
Etc/Greenwich
Etc/UCT
Etc/UTC
Etc/Universal
Etc/Zulu
Europe/Amsterdam
Europe/Andorra
Europe/Astrakhan
Europe/Athens
Europe/Belfast
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Busingen
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki
Europe/Isle_of_Man
Europe/Istanbul
Europe/Jersey
Europe/Kaliningrad
Europe/Kiev
Europe/Kirov
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Mariehamn
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Nicosia
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/San_Marino
Europe/Sarajevo
Europe/Saratov
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Tiraspol
Europe/Ulyanovsk
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
GB
GB-Eire
GMT
GMT+0
GMT-0
GMT0
Greenwich
HST
Hongkong
Iceland
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Comoro
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Mayotte
Indian/Reunion
Iran
Israel
Jamaica
Japan
Kwajalein
Libya
MET
MST
MST7MDT
Mexico/BajaNorte
Mexico/BajaSur
Mexico/General
NZ
NZ-CHAT
Navajo
PRC
PST8PDT
Pacific/Apia
Pacific/Auckland
Pacific/Bougainville
Pacific/Chatham
Pacific/Chuuk
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Johnston
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Midway
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Pohnpei
Pacific/Ponape
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Saipan
Pacific/Samoa
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Truk
Pacific/Wake
Pacific/Wallis
Pacific/Yap
Poland
Portugal
ROC
ROK
Singapore
Turkey
UCT
US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Samoa
UTC
Universal
W-SU
WET
Zulu

---------------------------------




Python - OS Module

** OS Module


==========================================

import os

print(dir(os))

---------------------------------

['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

---------------------------------

==========================================

import os

print(os.getcwd())

---------------------------------

C:\Users\purunet\Documents\py1

---------------------------------

==========================================

import os

print(os.getcwd())

os.chdir('C:\\Users\\purunet\\Documents')

print(os.getcwd())

---------------------------------

C:\Users\purunet\Documents\py1
C:\Users\purunet\Documents

---------------------------------

==========================================

import os


os.chdir('C:\\Users\\purunet\\Documents')

print(os.listdir())

---------------------------------

['c', 'desktop.ini', 'MobaXterm', 'MOP', 'My Kindle Content', 'My Music', 'My Pictures', 'My Videos', 'py', 'py1', 'Sample9', 'samsung', '카카오톡 받은 파일']

---------------------------------

==========================================

import os


os.chdir('C:\\Users\\purunet\\Documents')

os.makedirs('py2/Sub-Dir-1')

print(os.listdir())

---------------------------------

['c', 'desktop.ini', 'MobaXterm', 'MOP', 'My Kindle Content', 'My Music', 'My Pictures', 'My Videos', 'py', 'py1', 'py2', 'Sample9', 'samsung', '카카오톡 받은 파일']

---------------------------------

==========================================

import os


os.chdir('C:\\Users\\purunet\\Documents')

os.removedirs('py2/Sub-Dir-1')

print(os.listdir())

---------------------------------

['c', 'desktop.ini', 'MobaXterm', 'MOP', 'My Kindle Content', 'My Music', 'My Pictures', 'My Videos', 'py', 'py1', 'Sample9', 'samsung', '카카오톡 받은 파일']

---------------------------------

==========================================

import os


os.chdir('C:\\Users\\purunet\\Documents')

os.rename('test.txt', 'demo.txt')

print(os.listdir())

---------------------------------

['c', 'demo.txt', 'desktop.ini', 'MobaXterm', 'MOP', 'My Kindle Content', 'My Music', 'My Pictures', 'My Videos', 'py', 'py1', 'Sample9', 'samsung', '카카오톡 받은 파일']

---------------------------------

==========================================

import os


os.chdir('C:\\Users\\purunet\\Documents')

print(os.stat('demo.txt'))


---------------------------------

os.stat_result(st_mode=33206, st_ino=14918173766019528, st_dev=2215536944, st_nlink=1, st_uid=0, st_gid=0, st_size=42048, st_atime=1585886192, st_mtime=1586499848, st_ctime=1585886192)

---------------------------------

==========================================

import os
from datetime import datetime

os.chdir('C:\\Users\\purunet\\Documents')

print(os.stat('demo.txt').st_size)
print(os.stat('demo.txt').st_mtime)

mod_time = os.stat('demo.txt').st_mtime

print(datetime.fromtimestamp(mod_time))

---------------------------------

42048
1586499848.4476466
2020-04-10 15:24:08.447647

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1')


for dirpath, dirnames, filenames in os.walk('C:\\Users\\purunet\\Documents\\py1'):
print('Current Path:' , dirpath)
print('Directories:', dirnames)
print('Files:', filenames)
print()

---------------------------------

Current Path: C:\Users\purunet\Documents\py1
Directories: ['__pycache__']
Files: ['cal.py', 'comprehensions.py', 'empty.py', 'my.py', 'my_module.py', 'new1.py', 'new2.py', 'new3.py', 'new4.py', 'new5.py', 'new6.py', 'os.py', 'slicing.py', 'string_formatting.py', 'string_slicing.py', 'temp.py']

Current Path: C:\Users\purunet\Documents\py1\__pycache__
Directories: []
Files: ['my_module.cpython-38.pyc']

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1')


print(os.environ.get('HOME'))


---------------------------------

None

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1')


print(os.path.basename('\\tmp\\test.txt'))

---------------------------------

test.txt

---------------------------------

==========================================

import os

os.chdir('C:\\Users\\purunet\\Documents\\py1')


print(os.path.basename('\\tmp\\test.txt'))

print(os.path.dirname('\\tmp\\test.txt'))

print(os.path.split('\\tmp\\test.txt'))

print(os.path.splitext('\\tmp\\test.txt'))

print(os.path.exists('\\tmp\\test.txt'))

print(os.path.isdir('\\tmp\\fgdfgdf'))

print(os.path.isfile('\\tmp\\fgdfgdf'))

print('-'*80)

print(dir(os.path))

---------------------------------

test.txt
\tmp
('\\tmp', 'test.txt')
('\\tmp\\test', '.txt')
False
False
False
--------------------------------------------------------------------------------

['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_abspath_fallback', '_get_bothseps', '_getfinalpathname', '_getfinalpathname_nonstrict', '_getfullpathname', '_getvolumepathname', '_nt_readlink', '_readlink_deep', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']
[Finished in 0.1s]

---------------------------------


Python - String Formatting

** String Formatting


==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is ' + person['name'] + ' and I am ' + str(person['age']) + ' years old.'

print(sentence)


---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])

print(sentence)

---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])

print(sentence)

---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is {0[name]} and I am {1[age]} years old.'.format(person, person)

print(sentence)

---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is {0[name]} and I am {0[age]} years old.'.format(person)

print(sentence)

---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

l = ['Jenn', 23]

sentence = 'My name is {0[0]} and I am {0[1]} years old.'.format(l)

print(sentence)

---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------


==========================================

class Person():

def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person('Jack', '33')

sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1)

print(sentence)

---------------------------------

My name is Jack and I am 33 years old.

---------------------------------

==========================================

sentence = 'My name is {name} and I am {age} years old.'.format(name='Jenn', age='30')

print(sentence)

---------------------------------

My name is Jenn and I am 30 years old.

---------------------------------

==========================================

person = {'name': 'Jenn', 'age': 23}

sentence = 'My name is {name} and I am {age} years old.'.format(**person)

print(sentence)

---------------------------------

My name is Jenn and I am 23 years old.

---------------------------------

==========================================

for i in range(1, 11):
sentence = 'The value is {}'.format(i)
print(sentence)

---------------------------------

The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
The value is 6
The value is 7
The value is 8
The value is 9
The value is 10

---------------------------------

==========================================

for i in range(1, 11):
sentence = 'The value is {:02}'.format(i)
print(sentence)


---------------------------------

The value is 01
The value is 02
The value is 03
The value is 04
The value is 05
The value is 06
The value is 07
The value is 08
The value is 09
The value is 10

---------------------------------

==========================================

for i in range(1, 11):
sentence = 'The value is {:03}'.format(i)
print(sentence)

---------------------------------

The value is 002
The value is 003
The value is 004
The value is 005
The value is 006
The value is 007
The value is 008
The value is 009
The value is 010

---------------------------------

==========================================

pi = 3.14159265

sentence = 'PI is equal to {:.2f}'. format(pi)

print(sentence)

---------------------------------

PI is equal to 3.14

---------------------------------

==========================================

sentence = '1 MB is equal to {:,} bytes'.format(1000**2)

print(sentence)

---------------------------------

1 MB is equal to 1,000,000 bytes

---------------------------------

==========================================

sentence = '1 MB is equal to {:,.2f} bytes'.format(1000**2)

print(sentence)

---------------------------------

1 MB is equal to 1,000,000.00 bytes

---------------------------------

==========================================

import datetime

my_date = datetime.datetime(2020, 5, 7, 5, 30, 30)

print(my_date)


---------------------------------

2020-05-07 05:30:30

---------------------------------

==========================================

import datetime

my_date = datetime.datetime(2020, 5, 7, 5, 30, 30)

sentence = '{:%B %d, %Y}'.format(my_date)

print(sentence)

---------------------------------

May 07, 2020

---------------------------------

==========================================

import datetime

my_date = datetime.datetime(2020, 5, 7, 5, 30, 30)

# May 07, 2020 fell on a Thursday and was the 128 day of the year.

sentence = '{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year'.format(my_date)

print(sentence)

---------------------------------

May 07, 2020 fell on a Thursday and was the 128 day of the year

---------------------------------


5/06/2020

Python - Sorting Lists, Tuples, and Objects

** Sorting Lists, Tuples, and Objects


==========================================


li = [9, 1, 8, 2, 7, 3, 6, 4, 5]

s_li = sorted(li)

print('Sorted Variable:\t', s_li)
print('Original Variable:\t', li)


---------------------------------

Sorted Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Original Variable: [9, 1, 8, 2, 7, 3, 6, 4, 5]

---------------------------------

==========================================

li = [9, 1, 8, 2, 7, 3, 6, 4, 5]

s_li = sorted(li)

print('Sorted Variable:\t', s_li)

li.sort()

print('Original Variable:\t', li)

---------------------------------

Sorted Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Original Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]

---------------------------------

==========================================

li = [9, 1, 8, 2, 7, 3, 6, 4, 5]

s_li = li.sort()

print('Sorted Variable:\t', s_li)

li.sort()

print('Original Variable:\t', li)

---------------------------------

Sorted Variable: None
Original Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]

---------------------------------

==========================================

li = [9, 1, 8, 2, 7, 3, 6, 4, 5]

s_li = sorted(li, reverse = True)

print('Sorted Variable:\t', s_li)

li.sort()

print('Original Variable:\t', li)

---------------------------------

Sorted Variable: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Original Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]

---------------------------------

==========================================

li = [9, 1, 8, 2, 7, 3, 6, 4, 5]

s_li = sorted(li, reverse = True)

print('Sorted Variable:\t', s_li)

li.sort(reverse = True)

print('Original Variable:\t', li)

---------------------------------

Sorted Variable: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Original Variable: [9, 8, 7, 6, 5, 4, 3, 2, 1]

---------------------------------

==========================================

tup = (9, 1, 8, 2, 7, 3, 6, 4, 5)

tup.sort()

---------------------------------

 tup.sort()
AttributeError: 'tuple' object has no attribute 'sort'

---------------------------------

==========================================

tup = (9, 1, 8, 2, 7, 3, 6, 4, 5)

s_tup = sorted(tup)

print('Tuple:\t', s_tup)

---------------------------------

Tuple: [1, 2, 3, 4, 5, 6, 7, 8, 9]

---------------------------------

==========================================

di = {'name': 'Corey', 'job': 'programming', 'age': None, 'os': 'Mac'}

s_di = sorted(di)

print('Dict:\t', s_di)

---------------------------------

Dict: ['age', 'job', 'name', 'os']

---------------------------------

==========================================

li = [-6, -5, -4, 1, 2, 3]

s_li = sorted(li)

print(s_li)

---------------------------------

[-6, -5, -4, 1, 2, 3]

---------------------------------

==========================================

li = [-6, -5, -4, 1, 2, 3]

s_li = sorted(li, key = abs)

print(s_li)

---------------------------------

[1, 2, 3, -4, -5, -6]

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

s_employees = sorted(employees)

print(s_employees)

---------------------------------

s_employees = sorted(employees)
TypeError: '<' not supported between instances of 'Employee' and 'Employee'

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

def e_sort(emp):
return emp.name

s_employees = sorted(employees, key=e_sort)

print(s_employees)

---------------------------------

[(Carl, 37, $70000), (John, 43, $90000), (Sarah, 29, $80000)]

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

def e_sort(emp):
return emp.age

s_employees = sorted(employees, key=e_sort)

print(s_employees)

---------------------------------

[(Sarah, 29, $80000), (Carl, 37, $70000), (John, 43, $90000)]

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

def e_sort(emp):
return emp.salary

s_employees = sorted(employees, key=e_sort)

print(s_employees)

---------------------------------

[(Carl, 37, $70000), (Sarah, 29, $80000), (John, 43, $90000)]

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

def e_sort(emp):
return emp.salary

s_employees = sorted(employees, key=e_sort, reverse = True)

print(s_employees)

---------------------------------

[(John, 43, $90000), (Sarah, 29, $80000), (Carl, 37, $70000)]

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

def e_sort(emp):
return emp.salary

s_employees = sorted(employees, key=lambda e: e.name)

print(s_employees)

---------------------------------

[(Carl, 37, $70000), (John, 43, $90000), (Sarah, 29, $80000)]

---------------------------------

==========================================

class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return '({}, {}, ${})'.format(self.name, self.age, self.salary)

from operator import attrgetter

e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)

employees = [e1, e2, e3]

# def e_sort(emp):
# return emp.salary

s_employees = sorted(employees, key = attrgetter('age'))

print(s_employees)

---------------------------------

[(Sarah, 29, $80000), (Carl, 37, $70000), (John, 43, $90000)]

---------------------------------


Python - Comprehensions

** Comprehensions


==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n' for each 'n' in nums

my_list = []

for n in nums:
my_list.append(n)

print(my_list)

---------------------------------

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

---------------------------------

==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n' for each 'n' in nums

my_list = [n for n in nums]

print(my_list)

---------------------------------

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

---------------------------------

==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n*n' for each 'n' in nums

my_list = []

for n in nums:
my_list.append(n*n)

print(my_list)

---------------------------------

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

---------------------------------

==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n*n' for each 'n' in nums

my_list = [n*n for n in nums]

print(my_list)

---------------------------------

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

---------------------------------

==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# Using a map + lambda

my_list = list(map(lambda n: n*n, nums))

print(my_list)


---------------------------------

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

---------------------------------

==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n' for each 'n' in nums if 'n' is even

my_list = []

for n in nums:
if n%2 == 0:
my_list.append(n)

print(my_list)

---------------------------------

[2, 4, 6, 8, 10]

---------------------------------

==========================================

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n' for each 'n' in nums if 'n' is even

my_list = [n for n in nums if n%2 == 0]

print(my_list)

---------------------------------

[2, 4, 6, 8, 10]

---------------------------------

==========================================

ums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


# I want 'n' for each 'n' in nums if 'n' is even

my_list = list(filter(lambda n: n%2 == 0, nums))

print(my_list)

---------------------------------

[2, 4, 6, 8, 10]

---------------------------------

==========================================

# I want a (letter, num) pair for each letter in 'abcd' and each number in '0123'

my_list = []

for letter in 'abcd':
for num in range(4):
my_list.append((letter, num))

print(my_list)

---------------------------------

[('a', 0), ('a', 1), ('a', 2), ('a', 3), ('b', 0), ('b', 1), ('b', 2), ('b', 3), ('c', 0), ('c', 1), ('c', 2), ('c', 3), ('d', 0), ('d', 1), ('d', 2), ('d', 3)]

---------------------------------

==========================================

# I want a (letter, num) pair for each letter in 'abcd' and each number in '0123'

my_list = [(letter, num) for letter in 'abcd' for num in range(4)]


print(my_list)


---------------------------------

[('a', 0), ('a', 1), ('a', 2), ('a', 3), ('b', 0), ('b', 1), ('b', 2), ('b', 3), ('c', 0), ('c', 1), ('c', 2), ('c', 3), ('d', 0), ('d', 1), ('d', 2), ('d', 3)]


---------------------------------

==========================================

# Dictionary Comprehensions

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

print(list(zip(names, heros)))

---------------------------------

[('Bruce', 'Batman'), ('Clark', 'Superman'), ('Peter', 'Spiderman'), ('Logan', 'Wolverine'), ('Wade', 'Deadpool')]

---------------------------------

==========================================

# Dictionary Comprehensions

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

# I want a dict{'name': 'hero'} for each name, hero in zip(names, heros)

my_dict = {}
for name, hero in zip(names, heros):
my_dict[name] = hero

print(my_dict)


---------------------------------

{'Bruce': 'Batman', 'Clark': 'Superman', 'Peter': 'Spiderman', 'Logan': 'Wolverine', 'Wade': 'Deadpool'}

---------------------------------

==========================================

# Dictionary Comprehensions

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

# I want a dict{'name': 'hero'} for each name, hero in zip(names, heros)

my_dict = {name: hero for name, hero in zip (names, heros)}

print(my_dict)

---------------------------------

{'Bruce': 'Batman', 'Clark': 'Superman', 'Peter': 'Spiderman', 'Logan': 'Wolverine', 'Wade': 'Deadpool'}

---------------------------------

==========================================

# Dictionary Comprehensions

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

# I want a dict{'name': 'hero'} for each name, hero in zip(names, heros)
# If name not equal to Peter

my_dict = {name: hero for name, hero in zip (names, heros) if name != 'Peter'}

print(my_dict)

---------------------------------

{'Bruce': 'Batman', 'Clark': 'Superman', 'Logan': 'Wolverine', 'Wade': 'Deadpool'}

---------------------------------

==========================================

# Set Comprehensions

nums = [1, 1, 2, 1, 3, 4, 3, 4, 5, 5, 6, 7, 8, 7, 9, 9]
my_set = set()

for n in nums:
my_set.add(n)

print(my_set)

---------------------------------

{1, 2, 3, 4, 5, 6, 7, 8, 9}

---------------------------------

==========================================

# Set Comprehensions

nums = [1, 1, 2, 1, 3, 4, 3, 4, 5, 5, 6, 7, 8, 7, 9, 9]

my_set = {n for n in nums}

print(my_set)

---------------------------------

{1, 2, 3, 4, 5, 6, 7, 8, 9}

---------------------------------

==========================================

# Generator Expressions
# I want to yield 'n*n' for each 'n' in nums

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def gen_func(nums):
for n in nums:
yield n*n

my_gen = gen_func(nums)

for i in my_gen:
print(i)

---------------------------------

1
4
9
16
25
36
49
64
81
100

---------------------------------

# Generator Expressions
# I want to yield 'n*n' for each 'n' in nums

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


my_gen = (n*n for n in nums)

for i in my_gen:
print(i)


==========================================

---------------------------------

1
4
9
16
25
36
49
64
81
100

---------------------------------


Python - Slicing Lists and Strings

** Slicing Lists and Strings




==========================================

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#           0, 1, 2, 3, 4, 5, 6, 7, 8, 9
#        -10,-9,-8,-7,-6,-5,-4,-3,-2,-1                       

# list[start:end:step]


print(my_list)

print('-'*80)

print(my_list[0])
print(my_list[5])

print('-'*80)

print(my_list[-1])
print(my_list[-10])

print('-'*80)

print(my_list[0:6])
print(my_list[3:8])

print('-'*80)

print(my_list[-7:-2])
print(my_list[1:-2])
print(my_list[1:9])

print('-'*80)

print(my_list[1:])
print(my_list[5:])

print('-'*80)

print(my_list[-1:])

print('-'*80)

print(my_list[2:-1:2])
print(my_list[2:-1:1])
print(my_list[-1:2:-1])
print(my_list[-2:1:-2])

print('-'*80)

print(my_list[::-1])


---------------------------------

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
--------------------------------------------------------------------------------
0
5
--------------------------------------------------------------------------------
9
0
--------------------------------------------------------------------------------
[0, 1, 2, 3, 4, 5]
[3, 4, 5, 6, 7]
--------------------------------------------------------------------------------
[3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
--------------------------------------------------------------------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
--------------------------------------------------------------------------------
[9]
--------------------------------------------------------------------------------
[2, 4, 6, 8]
[2, 3, 4, 5, 6, 7, 8]
[9, 8, 7, 6, 5, 4, 3]
[8, 6, 4, 2]
--------------------------------------------------------------------------------
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

---------------------------------

==========================================

sample_url = 'https://google.com'
print(sample_url)

print('-'*80)

# Reverse the url
print(sample_url[::-1])

print('-'*80)

# Get the top level domain
print(sample_url[-4:])

print('-'*80)

# Print the url without the https://
print(sample_url[8:])

print('-'*80)

# Print the url without the https:// or the top level domain
print(sample_url[8:-4])

print('-'*80)


---------------------------------

https://google.com
--------------------------------------------------------------------------------
moc.elgoog//:sptth
--------------------------------------------------------------------------------
.com
--------------------------------------------------------------------------------
google.com
--------------------------------------------------------------------------------
google
--------------------------------------------------------------------------------

---------------------------------