一些简单的Python技巧

对象 and 对象.属性

class Animal:
    name = 'Tom'


a1 = Animal()
a2 = None

ret1 = a1 and a1.name
ret2 = a2 and a2.name

# Notice 如果对象为None就返回None,如果对象不为None就返回对应属性的值(属性必须在对象中定义,否则会抛异常!)
print('ret1:>>> ', ret1, type(ret1))  # Tom <class 'str'>
print('ret2:>>> ', ret2, type(ret2))  # None <class 'NoneType'>

开始时间的秒固定为0

from datetime import datetime
now = datetime.now()
# 重置秒和微秒为 0,精确到分钟
now = now.replace(second=0, microsecond=0)

print('now:>>> ', now) # 2026-05-15 15:49:00

~~~

~~~

posted on 2026-05-15 15:52  江湖乄夜雨  阅读(10)  评论(0)    收藏  举报