11, Getting started with Python - Advanced

Posted by Black Rider on Wed, 15 Apr 2020 17:06:18 +0200

Advanced

Date and time

import datetime
import time  # Introduce time Modular
import calendar

#Get current date time
now=datetime.datetime.now()
print(now)

#Get the specified date
d=datetime.datetime(2019,10,1,12,23,40)
print(d)

#Date to string
d2=d.strftime("%Y/%m/%d %H:%M:%S")
print(d2)

#String to date
s="2020-8-15 2:30:20"
d3=datetime.datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
print(d3)

#Get local time
ticks = time.time()
print ("The current timestamp is:", ticks)

localtime = time.localtime(time.time())
print ("Local time is :", localtime)

#Format
localtime = time.asctime( time.localtime(time.time()) )
print ("Local time is :", localtime)

# Format as 2016-03-20 11:45:39 form
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# Formatted into Sat Mar 28 22:24:24 2016 form
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
  
# Convert format string to timestamp
a = "Sat Mar 28 22:24:24 2016"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

cal = calendar.month(2016, 1)
print ("The following outputs the calendar for January 2016:")
print (cal)

CGI programming

CGI(Common Gateway Interface), a general gateway interface, is a program running on the server, such as HTTP server, which provides the interface with the client HTML page.

JSON

A data structure, convenient for data transmission, similar to the dictionary in python

#json,A string with a specific structure
import    json

#json Turn dictionary
j='{"city":"Beijing","weather":"Fine"}'
p=json.loads(j)
print(p)

#Dictionary turn json
d={"city":"Beijing","weather":"Fine"}
j2=json.dumps(d,ensure_ascii=False)
print(j2)

XML analysis

XML refers to EXtensible Markup Language, which is similar to HTML. XML is designed to transfer data, not display data

regular expression

Regular expression is a special character sequence, which can help you easily check whether a string matches a certain pattern.

MySql

Use mysql.connector or pymysql to connect

Encoding and decoding

encode() encoding

decode() decode

#Code
str1="It's off work, brother die"
str2=str1.encode("utf-8")
print(str2)

#Decode
str3=str2.decode("utf-8")
print(str3)

Topics: Python JSON xml MySQL encoding