The expression of time :
import time # Time stamp time.time() 1565141637.870625 # UTC Time time.ctime() # Return current time 'Wed Aug 7 09:34:59 2019' # 9 Tuples time.localtime() # At the present time 9 Tuples , In parentheses are the attributes owned by the time object time.struct_time(tm_year=2019, tm_mon=8, tm_mday=7, tm_hour=9, tm_min=35, tm_sec=39, tm_wday=2, tm_yday=219, tm_isdst=0) t1 = time.localtime() t1.tm_year 2019 t1.tm_yday 219
# sleep 3 second time.sleep(3)
# Converts the time to the specified string style
time.strftime('%Y-%m-%d %H:%M:%S') '2019-08-07 09:51:28' time.strftime('%a') 'Wed'
# Convert the time string to 9 Tuple time object
time.strptime('2019-08-07 10:17:23', '%Y-%m-%d %H:%M:%S') time.struct_time(tm_year=2019, tm_mon=8, tm_mday=7, tm_hour=10, tm_min=17, tm_sec=23, tm_wday=2, tm_yday=219, tm_isdst=-1) ```
>>> from datetime import datetime
>>> from datetime import datetime
>>> t = datetime.now()
>>> t # In parentheses is datetime Object properties
datetime.datetime(2019, 8, 7, 10, 56, 27, 91802)
>>> t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond (2019, 8, 7, 10, 56, 27, 91802)
# obtain datetime Object corresponding to the time string
>>> t.strftime('%Y-%m-%d %H:%M:%S') '2019-08-07 10:56:27'
# Convert the time string to datetime object
>>> datetime.strptime('2019-8-7', '%Y-%m-%d') datetime.datetime(2019, 8, 7, 0, 0)
# 100 God 3 Hours ago 、 Time after
>>> from datetime import datetime, timedelta
>>> days = timedelta(days=100, hours=3)
>>> t = datetime.now()
>>> t - days
datetime.datetime(2019, 4, 29, 8, 24, 9, 967534)
>>> t + days
datetime.datetime(2019, 11, 15, 14, 24, 9, 967534)
What if the program reports an error ?
No exception handling , The program crashes and terminates execution when it encounters an error . Exception handling requires finding problems , And give the coding scheme to solve the problem , Make the program When encountering errors again , It won't break down , Can still continue down .
Complete code for exception handling :
try:
Statements that may have exceptions
except abnormal 1:
Processing code
except ( abnormal 2, abnormal 3): Processing code
... ...
except abnormal n:
Processing code
else:
Code executed without exception
finally:
Code that executes whether or not an exception occurs
Access to the file system is mostly through python Of os Module implementation .
>>> import os
>>> os.getcwd() # pwd '/var/ftp/nsd2019/nsd1903/python02/day01'
>>> os.listdir() # ls
>>> os.listdir('/tmp') # ls /tmp
>>> os.mkdir('/tmp/demo')
>>> os.makedirs('/tmp/aaaa/bbb/ccc') # mkdir -p
>>> os.chdir('/tmp/demo') # cd /tmp/demo
>>> os.listdir() # ls
>>> import shutil
>>> shutil.copy('/etc/passwd', '.')
>>> os.listdir()
>>> os.symlink('/etc/hosts', 'zhuji') # ln -s /etc/hosts zhuji
>>> os.mkdir('abc')
>>> os.listdir() ['passwd', 'zhuji', 'abc']
>>> os.rmdir('abc') # rmdir abc Only empty directories can be deleted
>>> os.remove('zhuji') # rm -rf zhuji
>>> os.path.basename('/tmp/demo/abc.txt') # Return the filename section
'abc.txt'
>>> os.path.dirname('/tmp/demo/abc.txt') # Return to the path section
'/tmp/demo'
>>> os.path.split('/tmp/demo/abc.txt') # cutting
('/tmp/demo', 'abc.txt')
>>> os.path.abspath('.') # Returns the absolute path of the current path
'/tmp/demo'
>>> os.path.abspath('passwd') # Returns the absolute path of the file in the current directory
'/tmp/demo/passwd'
>>> os.path.join('/tmp/demo', 'abc.txt') # Splicing path
'/tmp/demo/abc.txt'
>>> os.path.isabs('passwd') # Is it an absolute path ?
False
>>> os.path.isfile('/etc/hosts') # Exists and is it a file ?
True
>>> os.path.ismount('/') # Is it a mount point ?
True
>>> os.path.isdir('/etc/abcd') # Exists and is it a directory ?
False
>>> os.path.islink('/etc/grub2.cfg') # Is there a link ?
True
>>> os.path.exists('/etc/') # Does it exist ?
True
It can write any data type to a file , And can be taken out without damage .
>>> f = open('/tmp/myfil', 'w')
>>> f.write('Hello World.\n') 13
# Regular file operations , Only characters can be written to a file , Cannot write other data types
>>> f.write(100) # Report errors
>>> f.write({'name': 'tom', 'age': 20}) # Report errors
>>> f.close()
# Use pickle Module operation
>>> import pickle
>>> user = {'name': 'tom', 'age': 20} # Write dictionary to file
>>> with open('/tmp/myfile', 'wb') as f:
... pickle.dump(user, f)
# Take the dictionary out of the file
>>> with open('/tmp/myfile', 'rb') as f:
... mydict = pickle.load(f)
>>> mydict
{'name': 'tom', 'age': 20}
practice : Bookkeeping procedure
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 2
date income spending balance explain
2019-8-7 0 0 10000 initialization
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 1
amount of money :100
remarks : Buying flowers on Tanabata
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 2
date income spending balance explain
2019-8-7 0 0 10000 initialization
2019-8-7 0 100 9900 Buying flowers on Tanabata
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 0
amount of money :10000
remarks : Wages
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 2
date income spending balance explain
2019-8-7 0 0 10000 initialization
2019-8-7 0 100 9900 Buying flowers on Tanabata
2019-8-7 10000 0 19900 Wages
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 3
Bye-bye
def save():
def cost():
def query():
def show_menu():
if __name__ == '__main__':
show_menu()
# Save each row of data into a small list , All rows are stored in a large list
records = [
['2019-8-7', 0, 0, 10000, 'init'],
['2019-8-7', 0, 100, 9900, 'buy flowers'],
['2019-8-7', 10000, 0, 19900, 'salary'],
]
# Take out the latest balance
>>> records[-1][-2]
19900
# Take out the time
>>> import time
>>> time.strftime('%Y-%m-%d')
'2019-08-07'
import os
from time import strftime
import pickle
def save(fname):
amount = int(input(' amount of money :'))
comment = input(' remarks :')
date = strftime('%Y-%m-%d')
with open(fname,'rb') as fobj:
records = pickle.load(fobj)
balance = records[-1][-2] + amount
records.append([date,amount,0,balance,comment])
with open(fname,'wb') as fobj:
pickle.dump(records,fobj)
def cost(fname):
amount = int(input(' amount of money :'))
comment = input(' remarks :')
date = strftime('%Y-%m-%d')
with open(fname, 'rb') as fobj:
records = pickle.load(fobj)
balance = records[-1][-2] - amount
records.append([date, 0, amount, balance, comment])
with open(fname, 'wb') as fobj:
pickle.dump(records, fobj)
def query(fname):
with open(fname,'rb') as fobj:
records = pickle.load(fobj)
print('%-12s%-8s%-8s%-10s%-20s' % ('date','save','cost','balance','comment'))
for record in records:
print('%-12s%-8s%-8s%-10s%-20s' % tuple(record))
def show_menu():
fname = 'account.data
init_data = [[strftime('%Y-%m-%d'),0,0,10000,'init']]
if not os.path.exists(fname):
with open(fname,'wb') as fobj:
pickle.dump(init_data,fobj)
cmds = {'0':save,'1':cost,'2':query}
prompt = '''
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):'''
while True:
choice = input(prompt).strip()
if choice not in ['0','1','2','3']:
print(' Invalid input , Please try again !')
continue
if choice == '3':
print('\nBye-bye')
break
cmds[choice](fname)
if __name__ == '__main__':
show_menu()
verification :
$ python 2-1.py
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):2
date save cost balance comment
2019-08-07 0 0 10000 init
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):0
amount of money :10000
remarks :gongzi
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):2
date save cost balance comment
2019-08-07 0 0 10000 init
2019-08-07 10000 0 20000 gongzi
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):1
amount of money :100
remarks :qixi
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):2
date save cost balance comment
2019-08-07 0 0 10000 init
2019-08-07 10000 0 20000 gongzi
2019-08-07 0 100 19900 qixi
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):2
date save cost balance comment
2019-08-07 0 0 10000 init
2019-08-07 10000 0 20000 gongzi
2019-08-07 0 100 19900 qixi
(0) income
(1) spending
(2) Inquire about
(3) sign out
Please select (0/1/2/3):3
Bye-bye