Python
How-to
String
data struct
Sorting Techniques — Python 3.12.3 documentation
datetime, time, calendar
找每個月的最後一天是幾號
import calendar
week_day_of_first_day, num_days = calendar.monthrange(year, month)
# weekday_of_first_day: 0-6 (Mon...)
file and directories
mkdir
Path.mkdir(parents=True, exist_ok=True) # parents=True: mkdir -p, exist_ok: ignore error if folder exist
copy files or folder
via: https://stackoverflow.com/a/123212/644070
import shutil
shutil.copyfile(src, dst)
# 2nd option
shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp
Issues
函式預設輸入值如果是 list
、dictionary
、instance of most classes
(mutable object),在函式定義的時候就建立了,之後載呼叫同一個函式會持續保留裡面的數值。
ref: - chatGPT: https://chat.openai.com/share/4be34b81-3eb6-4d99-99cf-20881e2fc831 - python docs: https://docs.python.org/3/tutorial/controlflow.html#default-argument-values
datetime
datetime — Basic date and time types — Python documentation
strptime
datetime.strptime(row['last_login'], '%Y-%m-%d %H:%M:%S+00') # 2021-01-01 12:03:34+00
datetime.strptime(row['created_time'], '%Y-%m-%d %H:%M:%S.%f+00') # # 2021-01-01 12:03:34.934533+00
csv
BOM header
Packages
PIL, PILLOW
Image.ANTIALIAS
新版改成 Image.Resampling.LANCZOS
Build exe file
- Nuitka/Nuitka: Nuitka is a Python compiler written in Python.
- PyInstaller より圧倒的に優れている Nuitka の使い方とハマったポイント | つくみ島だより
GUI
SQLAlchemy
join
query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
and_(
UserSong.user_id == user.id,
UserSong.is_liked.is_(True),
Song.genre == 'rock'
)
)
join, group by
session.query(Collection.name, func.count(Record.collection_id)).select_from(Record).join(Record.collection).group_by(Collection).all()
Note: important to place with_entities
after the join
query = query.with_entities(func.count())
liked_count = query.scalar()
sql_qry = select([foo.c.id.label("id"),
foo.c.title.label("title"),
bar.c.name.label("name")],
foo.c.id == bar.c.foo_id)
my_result_qry = session.query(MyResult).from_statement(sql_qry)
ref:
Celery
tatal: {'task.xxx': 數字} -> 執行的次數
JSON
要加astext
不然找不到 (就如同->>
, 沒加astext就是->
)
要重新給一個值,不然程式會以為沒變
Update json field data
record = session.query(YourModel).first()
record.data = {**record.data, "new_key": "new_value"} # Reassign with a new dictionary
session.commit()
Reference
Learning Resource
- Ten thousand meters - Python behind the scenes
- dabeaz-course/python-mastery: Advanced Python Mastery (course by @dabeaz) exercise codes with PDF
- Code Review of Senior Python Engineers
Related with R
- Statistics in Python with R, Liang Bo Wang Python與R的關係,強項在那裡